【发布时间】:2017-03-31 07:14:18
【问题描述】:
我好像做错了什么。我有一个使用 urllib 提取的 HTML 源代码。基于这个 HTML 文件,我使用 beautifulsoup 来查找具有基于指定数组的 ID 的所有元素。这对我有用,但是输出很混乱,并且包括换行符“\n”。
- Python: 2.7.12
- BeautifulSoup: bs4
我尝试使用 prettify() 来更正输出但总是报错:
AttributeError:“ResultSet”对象没有“prettify”属性
import urllib
import re
from bs4 import BeautifulSoup
cfile = open("test.txt")
clist = cfile.read()
clist = clist.split('\n')
i=0
while i<len (clist):
url = "https://example.com/"+clist[i]
htmlfile = urllib.urlopen (url)
htmltext = htmlfile.read()
soup = BeautifulSoup (htmltext, "html.parser")
soup = soup.findAll (id=["id1", "id2", "id3"])
print soup.prettify()
i+=1
我确信我忽略了这一行的一些简单的东西:
soup = soup.findAll (id=["id1", "id2", "id3"])
我只是不确定是什么。对不起,如果这是一个愚蠢的问题。我只用了几天 Python 和 Beautiful Soup。
【问题讨论】:
-
拨打
findAll()后soup的类型是什么?运行type(soup)。 -
"输出很乱,包括换行符 "\n"" - 哪个输出?你从哪里得到这个你不满意的输出?唯一可以在您给出的代码中输出任何内容的是
print soup.prettify(),因为您说它会引发错误,所以这不可能。你最终想要做什么?如果在每个元素上使用.text属性会怎样? -
@CivFan 肯定是
ResultSet? -
@AlexHall 只是试图引导 Eric 找到他自己的答案。
alecxe在他的回答中指出了这一点。
标签: python beautifulsoup