【发布时间】:2015-09-04 17:57:36
【问题描述】:
我使用 BeautifulSoup 将网站上的一些文本(城市名称)解析为列表,但遇到了一个我无法克服的问题。网站上的文本元素有特殊字符,当我打印列表时,城市名称显示为 [u'London],而不是特殊字符,出现了数字和字母。如何去掉开头的“u”,将文本转换为网站上最初显示的格式?
代码如下:
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']
例如,底部的第 7 个元素 [u'Nyiregyh\xe1za'] 显示不正确。
【问题讨论】:
-
u 前缀仅用于源代码;如果您看到它,那是因为您正在打印对象的表示。 Unicode HOWTO 有帮助吗?如果您想要的不仅仅是指向有关编码字符的文档的一般指针,您可能需要显示一些代码。
标签: python unicode beautifulsoup special-characters