如何将BeautifulSoup.ResultSet转换为字符串

2024-04-24 17:26:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我将一个带有.findAll(BeautifulSoup)的html页面解析为名为result的变量。 如果我在Python shell中键入result,然后按Enter键,我将看到预期的正常文本,但由于我想将此结果作为string对象进行后处理,我注意到str(result)返回垃圾,如以下示例:

\xd1\x87\xd0\xb8\xd0\xbb\xd0\xbd\xd0\xb8\xd1\x86\xd0\xb0</a><br />\n<hr />\n</div>

Html页源是utf-8编码的

我该怎么办?


代码基本上是这样的,如果重要的话:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(urllib.open(url).read())
result = soup.findAll(something)

Python是2.7


Tags: 对象文本string键入html页面resultshell
3条回答

Python2.6.7 美化组。版本3.2.0

这对我有效:

unicode.join(u'\n',map(unicode,result))

我很确定result是一个BeautifulSoup.ResultSet对象,它似乎是标准python列表的扩展

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(urllib.open(url).read())
#findAll should get multiple parsed result
result = soup.findAll(something)
#then iterate result
for line in result:
    #get str value from each line,replace charset with utf-8 or other charset you need
    print line.__str__('charset')

顺便说一句:美组的版本是美组-3.2.1

那不是垃圾,那是UTF-8编码的文本。Use Unicode instead.

相关问题 更多 >