# 需求 :图片数据解析http://pic.netbian.com/4kmeinv/
import requests
import os
from lxml import etree
if __name__ == "__main__":
# 爬取页面源码数据
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
} # UA伪装
url = 'http://pic.netbian.com/4kmeinv/'
page_text = requests.get(url=url,headers = headers).text
# 手动设定响应数据的编码格式
# res = requests.get(url=url,headers = headers)
# res.encoding = 'utf-8'
# page_text = res.text
# 页面数据解析
tree = etree.HTML(page_text)
# 创建一个文件夹
if not os.path.exists('./girlpiclib'):
os.mkdir('./girlpiclib')
li_list = tree.xpath('//div[@class="slist"]//li')
for li in li_list:
#局部解析 获取src 与 alt
img_src = li.xpath('./a/img/@src')[0]
img_name = li.xpath('./a/img/@alt')[0]+'.jpg'
# 通用处理中文乱码的解析方式
img_name = img_name.encode('iso-8859-1').decode('gbk')
url = 'http://pic.netbian.com/'+img_src
# 爬取图片数据content
pic_content = requests.get(url= url,headers = headers).content
#持久化存储
img_path = 'girlpiclib/' + img_name
fp = open(img_path,'wb')
fp.write(pic_content)
print(img_name,'下载成功')