今天帮群友解决一个lxml抓取所有文本时遇到的问题,lxml抓取中文会乱码,搜索一下,找到如下的解决方案,分享给大家。
1、要保证传给lxml的参数都是unicode
2、用 urlopen() 抓到的 file-like object ,或者用open()打开的硬盘上的 file object 不一定是unicode
3、用 unicode(file-like-object.read(),"utf-8") 能得到肯定是unicode的东西
4、这样处理之后再传给lxml的fromstring
5、xml.etree.ElementTree 也是一样
6、虽然lxml.html.parse()可以接受file-like object 作为参数,但是不要用,因为你传进去一个file-like object 你也不知道是不是unicode,万一有中文就会有乱码。
7、总是用unicode(file-like-object.read(),"utf-8") 这么转换对性能肯定是不好,但目前我也只会这种笨方法
应用到代码中如下,请大家参考:
01 |
#!/usr/bin/env python |
02 |
# -*- coding: utf-8 -*- |
03 |
# Date: 2016/2/14 |
04 |
# Created by 独自等待 |
05 |
# 博客 http://www.waitalone.cn/ |
06 |
import urllib2 |
07 |
from lxml import etree |
08 |
from lxml.html.clean import Cleaner |
09 |
10 |
11 |
def getText(url): |
12 |
''' |
13 |
获取指定url返回页的所有文字 |
14 |
:param url: 需要抓取的url |
15 |
:return: 返回文字 |
16 |
''' |
17 |
page = urllib2.urlopen(url, timeout = 10 ).read() |
18 |
page = unicode (page, "utf-8" ) # 转换编码,否则会导致输出乱码 |
19 |
cleaner = Cleaner(style = True , scripts = True , page_structure = False , safe_attrs_only = False ) # 清除掉CSS等 |
20 |
str = etree.HTML(cleaner.clean_html(page)) |
21 |
texts = str .xpath( '//*/text()' ) # 获取所有文本 |
22 |
for t in texts: |
23 |
print t.strip().encode( 'gbk' , 'ignore' ) |
24 |
25 |
26 |
getText( 'http://www.360.cn/' ) |
参考文章: