【发布时间】:2012-12-24 14:48:06
【问题描述】:
我正在学习 python 并使用 BeautifulSoup 来抓取一些网页。我要做的是找到第一个'td'的子'a',提取href并将其添加到列表中。如何以及在何处将 href 添加到单元格文本?
import urllib2
from BeautifulSoup import BeautifulSoup
def listify(table):
"""Convert an html table to a nested list"""
result = []
rows = table.findAll('tr')
for row in rows:
result.append([])
cols = row.findAll('td')
for col in cols:
strings = [_string.encode('utf8') for _string in col.findAll(text=True)]
text = ''.join(strings)
result[-1].append(text)
return result
【问题讨论】:
-
cols[1].find('a')['href']应该可以解决问题 -
有什么理由不使用 BeautifulSoup 4 而不是 3?
-
对 bs4 的好评。我都下载了,但安装了 3。现在使用 4。
标签: python beautifulsoup href urllib2