1.參考
Beautiful Soup and Unicode Problems
詳細解釋
unicodedata.normalize('NFKD',string) 實際作用???
Scrapy : Select tag with non-breaking space with xpath
>>> selector.xpath(u'''
... //p[normalize-space()]
... [not(contains(normalize-space(), "\u00a0"))]
normalize-space() 實際作用???
In [244]: sel.css('.content')
Out[244]: [Selector xpath=u"descendant-or-self::*[@class and contains(concat(' ', normalize-space(@class), ' '), ' content ')]" data=u'p class="content text-
BeautifulSoup下Unicode亂碼解決
今天在用scrapy爬某個網站的數據,其中DOM解析我用的是BeautifulSoup,速度上沒有XPath來得快,不過因為用了習慣了,所以一直用的bs,版本是bs4
不過在爬取過程中遇到了一些問題,其中一個是Unicode轉碼問題,這也算是python中一個著名問題了。
我遇到的算是BeautifulSoup中的一個奇葩bug吧,在網頁中經常會有 nbsp 這種標記,稱為 non-breaking space character, 本來這個應該是忽略的,但在bs中會把這個符號
轉義成為一個unicode編碼 \xa0, 這就導致了后面如果要對內容處理的話會出現UnicodeError, 特別是如果使用的是Console或者scrapy中寫文件、寫數據庫的pipeline操作時,
出現無法轉義的錯誤。
那么該如何解決呢,其實不難
s = u'\xa0'
s.replace(u'\xa0', u'')
之后就可以對s進行encode,比如:
s = u'\xa0'
s.replace(u'\xa0', u'').encode('utf-8')
特別是在我的項目中,如果需要把數據寫到MongoDB中,這個bug fix完后,寫數據立刻搞定,爬取的內容全部寫到MongoDB中。
s.replace(u'\xa0', u'').encode('utf-8')
2.問題定位
https://en.wikipedia.org/wiki/Comparison_of_text_editors
定位元素顯示為 npsp;

網頁源代碼表示為 #160;
tr>
td style="background: #FFD; color: black; vertical-align: middle; text-align: center;" class="partial table-partial">memory/td>
td>= Limited by available memory #160;#160;/td>
td style="background:#F99;vertical-align:middle;text-align:center;" class="table-no">No (64#160;KB)/td>
td>= Some limit less than available memory (give max size if known)/td>
/tr>
/table>
實際傳輸Hex為:

不間斷空格的unicode表示為 u\xa0'
,保存的時候編碼 utf-8 則是 '\xc2\xa0
'
In [211]: for tr in response.xpath('//table[8]/tr[2]'):
...: print [u''.join(i.xpath('.//text()').extract()) for i in tr.xpath('./*')]
...:
[u'memory', u'= Limited by available memory \xa0\xa0', u'No (64\xa0KB)', u'= Some limit less than available memory (give max size if known)']
In [212]: u'No (64\xa0KB)'.encode('utf-8')
Out[212]: 'No (64\xc2\xa0KB)'
In [213]: u'No (64\xa0KB)'.encode('utf-8').decode('utf-8')
Out[213]: u'No (64\xa0KB)'
保存 csv 直接使用 excel 打開會有亂碼(默認ANSI gbk 打開???,u'\xa0' 超出 gbk 能夠編碼范圍???),使用記事本或notepad++能夠自動以 utf-8 正常打開。

使用記事本打開csv文件,另存為 ANSI 編碼,之后 excel 正常打開。超出 gbk 編碼范圍的替換為'?'

3.如何處理
.extract_first().replace(u'\xa0', u' ').strip().encode('utf-8','replace')
以上就是HTML轉義字符npsp;表示non-breaking space \xa0的詳細內容,更多關于HTML轉義字符\xa0的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:- Python 字符串處理特殊空格\xc2\xa0\t\n Non-breaking space