今天幫群友解決一個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/' ) |
參考文章: