#图片解析 import requests from lxml import etree import os if __name__ == '__main__': url='https://pic.netbian.com/4kmeishi/' headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36' } response=requests.get(url=url,headers=headers) #手动设定响应数据的编码格式,手动解决乱码的问题 #response.encoding='utf-8' page_text=response.text #实例化对象 tree=etree.HTML(page_text) li_list=tree.xpath('//div[@class="slist"]/ul/li') #创建一个文件夹 if not os.path.exists('./meishi.Libs/'): os.mkdir('./meishi.Libs/') for li in li_list: img_list='https://pic.netbian.com'+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') #请求图片进行持久化存储 img_date=requests.get(url=img_list,headers=headers).content #content对应的URL后缀一定是 JPG,如果是HTML一定会显示空白 img_path='./meishi.Libs/'+img_name with open(img_path,'wb')as fp: fp.write(img_date) print(img_name,'下载成功!')
代码如上,报错:
Traceback (most recent call last):
File "C:/Users/忙碌的小仙女/PycharmProjects/爬虫学习/xpath 案例2.py", line 18, in <module>
tree=etree.HTML(page_text)
AttributeError: 'function' object has no attribute 'HTML'