我正在尝试从这类 pages 中抓取信息.
我需要Internship
、Residency
、Fellowship
中包含的信息。我可以从表中提取值,但在这种情况下我无法决定使用哪个表,因为标题(如 Internship
)出现在表外的 div
标记下一个简单的纯文本,然后出现我需要提取其值的表。我有很多这样的页面,并且没有必要每个页面都有这些值,比如在某些页面中 Residency
可能根本不存在。 (这会减少页面中表格的总数)。此类页面的一个示例是 this .在此页面中,Internship
根本不存在。
我面临的主要问题是所有表都具有相同的属性值,因此我无法决定将哪个表用于不同的页面。如果页面中没有我感兴趣的任何值,我必须为该值返回一个空字符串。
我在 Python 中使用 BeautifulSoup。有人可以指出,我怎样才能继续提取这些值。
最佳答案
标题和数据的 ID 似乎都具有唯一值和标准后缀。您可以使用它来搜索适当的值。这是我的解决方案:
from BeautifulSoup import BeautifulSoup
# Insert whatever networking stuff you're doing here. I'm going to assume
# that you've already downloaded the page and assigned it to a variable
# named 'html'
soup = BeautifulSoup(html)
headings = ['Internship', 'Residency', 'Fellowship']
values = []
for heading in headings:
x = soup.find('span', text=heading)
if x:
span_id = x.parent['id']
table_id = span_id.replace('dnnTITLE_lblTitle', 'Display_HtmlHolder')
values.append(soup.find('td', attrs={'id': table_id}).text)
else:
values.append('')
print zip(headings, values)
关于python - 如何使用 BeautilSoup 提取表信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14947218/