lxml xpath 爬取并正常显示中文内容

 

在使用python爬虫提取中文网页的内容,为了能正确显示中文的内容,在转为字符串时一定要声明编码为utf-8,否则无法正常显示中文,而是显示原编码的字符,并没有正确转换。比如下面这个简单的爬取百度页面的title的示例:

 

import os
import lxml
from urllib2 import urlopen # Mac
# from urllib.request import Request, urlopen # Win
from lxml import etree

hfile = urlopen('http://www.baidu.com').read()
tree = etree.HTML(hfile)
strs = tree.xpath( "//title")
strs = strs[0]
# strs = (etree.tostring(strs)) # 不能正常显示中文
strs = (etree.tostring(strs, encoding = "utf-8", pretty_print = True, method = "html")) # 可以正常显示中文
print (strs)

 

如果不在tostring函数中正确配置的话,会打印出:

<title>&#30334;&#24230;&#19968;&#19979;&#65292;&#20320;&#23601;&#30693;&#36947;</title>

 

而正确的应该是:

<title>百度一下,你就知道</title>

 

转载于:https://www.cnblogs.com/grandyang/p/7990505.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值