我已經從使用BeautifulSoup的網站解析了一些文本(城市名稱)到列表中,但遇到了一個我無法克服的問題。網站上的文本元素有特殊字符,當我打印列表中的城市名被顯示爲[u'London]代替作爲特殊字符有數字和字母出現。如何在開始時擺脫「u」並將文本轉換爲最初出現在網站上的格式?Python中有特殊字符的字符串無法正確顯示
下面是代碼:
import urllib2
from bs4 import BeautifulSoup
address = 'https://clinicaltrials.gov/ct2/show/NCT02226120?resultsxml=true'
page = urllib2.urlopen(address)
soup = BeautifulSoup(page)
locations = soup.findAll('country', text="Hungary")
for city_tag in locations:
site=city_tag.parent.name
if site=="address":
desired_city=str(city_tag.findPreviousSibling('city').contents)
print desired_city
,這裏是我所得到的輸出:
[u'Pecs']
[u'Baja']
[u'Balatonfured']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Budapest']
[u'Cegled']
[u'Debrecen']
[u'Eger']
[u'Hodmezovasarhely']
[u'Miskolc']
[u'Nagykanizsa']
[u'Nyiregyh\xe1za']
[u'Pecs']
[u'Sopron']
[u'Szeged']
[u'Szekesfehervar']
[u'Szekszard']
[u'Zalaegerszeg']
從底部[u'Nyiregyh \ xe1za']例如第七元素不正確顯示。
在U前綴僅用於源代碼;如果你看到它,那是因爲你正在打印對象的表示。 [Unicode HOWTO](https://docs.python.org/2/howto/unicode.html#reading-and-writing-unicode-data)有幫助嗎?如果您不想在編碼字符上使用文檔的常規指針,您可能需要顯示一些代碼。 – dsh