网页爬虫 - python中使用lxml解析中文网页出现编码问题,如何解决?

查看:503
本文介绍了网页爬虫 - python中使用lxml解析中文网页出现编码问题,如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

问题

爬取IT之家网页http://it.ithome.com/category...
在使用requests.get得到网页后用lxml解析,但是打印出来后中文无法正常显示,
而打印requests.get得到的内容却可以正常显示。求原因及解决方法(BeautifulSoup可正常解析)。

代码

# coding: utf-8
import requests
from lxml import etree
from io import StringIO

init_url = 'http://it.ithome.com/category/31_4.html'
init_page = requests.get(init_url).text
print init_page.encode('utf-8')


parser = etree.HTMLParser()
html = etree.parse(StringIO(init_page), parser)
result = etree.tostring(html, pretty_print=True, method="html")
print result


news_titles = html.xpath('//div[@class="block"]/h2')
print len(news_titles)
for news_title in news_titles:
    print news_title.text

输出结果

  • 使用print init_page.encode('utf-8')能正常输出

  • 使用print result无法正常显示中文

解决方案

这句加上 encoding 参数

result = etree.tostring(html, encoding="gb2312", pretty_print=True, method="html")

我是Windows,所以用的gb2312,测试能正常显示, 如果你是linux, 改成utf-8

这篇关于网页爬虫 - python中使用lxml解析中文网页出现编码问题,如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆