今天早上,我花了幾個令人沮喪的時間,試圖處理來自刮網頁的字符串。我似乎無法得到一種降低提取的字符串的一致方式,因此我可以檢查關鍵字 - 並將其推動我轉彎。BeautifulSoupTag,字符串和UnicodeEncodeError不是很漂亮
下面是一個代碼片段,從一個DOM元素檢索文字:
temp = i.find('div', 'foobar').find('div')
if temp is not None and temp.contents is not None:
temp2 = whitespace.sub(' ', temp.contents[0])
content = str(temp2)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 150: ordinal not in range(128)
我也嘗試下面的語句 - 其中沒有工作;即,它們導致了同樣的錯誤被拋出:
content = (str(temp2)).decode('utf-8').lower()
content = str(temp2.decode('utf-8')).lower()
有誰知道如何包含在BeautifulSoupTag內成小寫ASCII德文本轉換,所以我可能會進行的關鍵字不區分大小寫的搜索?
嘗試在這裏找到了答案:[文件](http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful湯給你的Unicode,該死的) – methyl 2012-01-30 12:36:06
你能只需使用'unicode(temp2)'? – 2012-01-30 12:45:36
閱讀我的答案,你已經接受[你幾乎相同的問題](http://stackoverflow.com/q/9012607/4279) – jfs 2012-01-30 14:30:39