recherche

Maison  >  Questions et réponses  >  le corps du texte

网页爬虫 - 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('//p[@class="block"]/h2')
print len(news_titles)
for news_title in news_titles:
    print news_title.text

输出结果

大家讲道理大家讲道理2892 Il y a quelques jours515

répondre à tous(1)je répondrai

  • PHPz

    PHPz2017-04-18 09:15:54

    Ajouter un paramètre d'encodage à cette phrase

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

    Je suis sous Windows, j'utilise donc gb2312, et le test peut s'afficher normalement. Si vous êtes sous Linux, changez-le en utf-8

    .

    répondre
    0
  • Annulerrépondre