爬虫小技巧

处理乱码的一种方式

#处理中文乱码
import requests
from lxml import etree
url = 'http://pic.netbian.com/4kqiche/'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 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')
for li in li_list:
    img_src = li.xpath('./a/img/@src')[0]
    img_name = li.xpath('./a/b/text()')[0]
    #通用性
    img_name = img_name.encode('iso-8859-1').decode('gbk')
    print(img_src,img_name)

 

posted @ 2019-05-22 00:25  7411  阅读(104)  评论(0编辑  收藏  举报