如何使用beutilsoup提取表信息?

2024-04-26 04:57:05 发布

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

我试图从这类pages中搜集信息。你知道吗

我需要包含在InternshipResidencyFellowship下的信息。我可以从表中提取值,但在本例中,我无法决定使用哪个表,因为标题(如Internship)以简单的纯文本形式出现在表外的div标记下,然后出现需要提取其值的表。我有很多这样的页面,没有必要每个页面都有这些值,比如在一些页面Residency可能根本不存在。(这将减少页面中表的总数)。这种页面的一个例子是this。在这个页面中Internship根本不存在。你知道吗

我面临的主要问题是所有的表都有相同的属性值,所以我无法决定在不同的页面中使用哪个表。如果页面中没有我感兴趣的任何值,我必须为该值返回一个空字符串。你知道吗

我在Python中使用BeautifulSoup。有人能指出,我怎样才能继续提取这些值。你知道吗


Tags: 标记文本div信息标题页面pagesthis
1条回答
网友
1楼 · 发布于 2024-04-26 04:57:05

看起来标题和数据的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)

相关问题 更多 >