我已经从使用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