python - 如何使用 BeautilSoup 提取表信息?

标签 python web-scraping beautifulsoup

我正在尝试从这类 pages 中抓取信息.

我需要InternshipResidencyFellowship 中包含的信息。我可以从表中提取值,但在这种情况下我无法决定使用哪个表,因为标题(如 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/

相关文章:

java - jep在java中解释python时出错

python - 尝试抓取 Forecast.weather.gov 并遇到问题,特别是从 WriteText 标签获取数据时遇到问题

javascript - 查找链接所在位置

excel - 为什么我的使用 VBA 抓取文本的代码仅在调试中有效

python - 如何获取第一个span标签?

python - 如何将json数据从url打印到excel?

python - Django 1.9 教程 __str__ () 不工作

python - 从 VegasInsider 抓取表格

python - 如何使用 beautifulsoup 在 html 代码中添加背景颜色?

Python HTML 解析器分页