在Python和BeautifulSoup中迭代
soup = BeautifulSoup(html).findAll('div', 'thread')
for i in soup:
print i
我只想讨论这段代码,因为我在这里遇到了问题。
Soup返回的是一个列表,我试着用' '.join()把它变成一个字符串,但没有成功,因为它需要的是一个字符串,而不是标签。我觉得这有点像是个bug。
在循环中,它会把列表里的所有内容都打印出来,但没有逗号。
不过我想要的是获取
2 个回答
1
看看这个模块/类的文档(http://www.crummy.com/software/BeautifulSoup/documentation.html)——在findAll
这个函数里,第二个参数应该是一个json对象,而不是字符串。你试过这样做吗:
BeautifulSoup(html).findAll('div', { 'class': 'thread' })
2
应该是像这样的东西
divs = BeautifulSoup(html).findAll('div','thread')
for div in divs:
print div.find('a').attr['href'] # may it be map(a.attrs)['href'], I don't remember now