【发布时间】:2014-03-02 15:12:05
【问题描述】:
嗨,我正在使用 Beautifulsoup 解析网站并获取名称作为输出。但是在运行脚本之后,我得到了一个[u'word1', u'word2', u'word3'] 输出。我正在寻找的是'word1 word2 word3'。如何摆脱这个u' 并将结果变成一个字符串?
from bs4 import BeautifulSoup
import urllib2
import re
myfile = open("base/dogs.txt","w+")
myfile.close()
url="http://trackinfo.com/entries-race.jsp?raceid=GBR$20140302A01"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
names=soup.findAll('a',{'href':re.compile("dog")})
myfile = open("base/dogs.txt","w+")
for eachname in names:
d = (str(eachname.string.split()))+"\n"
print [x.encode('ascii') for x in d]
myfile.write(d)
myfile.close()
【问题讨论】:
-
print [str(x.encode('ascii')) for x in d]? -
请注意,如果您的字符串可以包含多字节字符,则将其从 Unicode 字符串更改为 ASCII 字符串实际上会破坏数据。你确定这是你想做的事吗?
-
请注意,如果你只是打印字符串——比如
print——或者直接写它们(不是作为对象的一部分,用repr()对其内容进行字符串化)——它们' 将显示为文字,而不是u''装饰。
标签: python web-scraping beautifulsoup