python爬虫xpath\lxml图片解析(处理乱码)

import requests
from lxml import etree
import os
import urllib
url = 'http://pic.netbian.com/4kmeinv/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
}
response = requests.get(url=url,headers=headers)
if not os.path.exists('./4ktu'):
    os.mkdir('./4ktu')
#页面编码为gbk,在这进行转码为全页面
#response.encoding = 'utf-8'
page_text= response.text
#etree.HTML是通过request获取的网页
tree = etree.HTML(page_text)
#etree.parse是用作本地已经拥有的HTML页面
#etree.parse()
li_list = tree.xpath('//div[@class="slist"]/ul/li')
for li in li_list:
    img_name = li.xpath('./a/b/text()')[0]
    # 页面编码为gbk,进行局部名字页面的转码。非全页面
    #处理中文乱码img_name.encode('iso-8859-1').decode('gbk')
    img_name = img_name.encode('iso-8859-1').decode('gbk')
    img_url = 'http://pic.netbian.com' + li.xpath('./a/img/@src')[0]
    #测试图片名字
    #print(img_name)
    img_path = './4ktu/'+img_name+'.jpg'
    urllib.request.urlretrieve(url=img_url,filename=img_path)
    print(img_path,'下载成功!')
print('over!!!')

说点什么

avatar
  Subscribe  
提醒