python lxml解析中文的问题
问题描述
使用lxml来抓取中文字符,抓到的结果很蛋疼,不知道怎么处理...
comUrl='http://m.51job.com/search/codetail.php?coid=4108723'res=requests.get(comUrl)html=etree.HTML(res.text)p=html.xpath('//aside')[1].xpath('./p') #结果为[<Element p at 0x7bf01c8>, <Element p at 0x78f4408>, <Element p at 0x69db388>]p[0].xpath('./span/text()') #这个是想要抓取的字符
结果抓到的是这样的 [u’xe6x80xa7xe8xb4xa8’]unicode但是内容是str的编码,请问怎么把这个东西转成中文?正常应该是’xe6x80xa7xe8xb4xa8’或者u’u6027u8d28’
问题解答
回答1:’’.join(map(lambda x:chr(x), map(lambda x:ord(x), u’xe6x80xa7xe8xb4xa8’))).decode(’utf-8’)回答2:
出现这种情况,一般是requests猜错了网页的编码了因此指定requests的编码就可以了.res.encoding =’utf-8’
In [33]: comUrl='http://m.51job.com/search/codetail.php?coid=4108723' ...: res=requests.get(comUrl) ...: res.encoding =’utf-8’ ...: html=etree.HTML(res.text) ...: p=html.xpath('//aside')[1].xpath('./p') #结果为[<Element p at 0x7b ...: f01c8>, <Element p at 0x78f4408>, <Element p at 0x69db388>] ...: p[0].xpath('./span/text()') #这个是想要抓取的字符 ...: Out[33]: [u’u6027u8d28’]In [34]: print _[0]性质
相关文章:
1. python - pip install出现下面图中的报错 什么原因?2. python - 怎样在linux下开发flask web应用时查看代码出错(traceback)的地方。3. python3.x - python多进程,不能在同一窗口吗4. mysql - 数据库字段命名问题,新人,求解5. python - nginx为什么不能反代图片?6. css - input中transition 设置background-color过渡,chrome浏览器页面初始化渲染会有过度效果7. Browser-sync安装失败问题8. windows-7 - Win7中Vmware Workstatoin与Xampp中Apache服务器端口冲突?9. 微信端电子书翻页效果10. html5 - api.douban.com/v2/movie/in_theaters?start=0&count=3 不在以下合法域名列表中

网公网安备