python的一次简单爬虫···

import requests
from lxml import etree

headers={
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0",
    "Referer":"https://www.mzitu.com/",
}
response = requests.get("https://www.mzitu.com/" , headers=headers)   #获得网页源码
# print(response.text) 查看是否录入网页源码

html = etree.HTML(response.text)
#response.text为字符串类型
#etree.HTML()可以用来解析字符串格式的HTML文档对象,将传进去的字符串转变成_Element对象。
#作为_Element对象,可以方便的使用getparent()、remove()、xpath()等方法。

src_list = html.xpath('//img[@class="lazy"]/@data-original')    
alt_list = html.xpath('//img[@class="lazy"]/@alt')
#xpath返回一个列表

for src,alt in zip(src_list,alt_list):
    response = requests.get(src, headers=headers)
    FileName = "img\\" + alt + ".jpg"
    print("正在保存图片:" + FileName)
    with open(FileName,"wb") as p:
    #二进制写入,说明response内容为二进制
    #text 返回的是unicode 型的数据,一般是在网页的header中定义的编码形式。content返回的是bytes,二进制型的数据。
        p.write(response.content)

   加油加油加油!!!

猜你喜欢

转载自www.cnblogs.com/xikl/p/12031556.html