【问题标题】:How do I extract a table using table id using BeautifulSoup如何使用 BeautifulSoup 使用表 id 提取表
【发布时间】:2018-05-10 05:23:20
【问题描述】:

我正在学习如何使用 BeautifulSoup 从https://afltables.com/afl/stats/teams/adelaide/2018_gbg.html 抓取表格。

这个特定页面有多个表格,我希望能够根据表格 ID 提取特定表格。检查代码时,我可以看到每个表都有一个唯一的 id。

我尝试了以下方法,它返回一个空列表:

import requests
from bs4 import BeautifulSoup
url="https://afltables.com/afl/stats/teams/adelaide/2018_gbg.html"
page=requests.get(url)
soup=BeautifulSoup(page.content, 'html.parser')

table=soup.find_all('table', id='sortableTable0')
print(table)

如果我按相同标签中的表类搜索,我可以提取所有表,所以我不确定为什么搜索特定表 id 不起作用?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    该表是通过 JavaScript 动态生成的,因此您需要使用可以处理它的东西。 Python 中的一种选择是使用Selenium,如下所示:

    from bs4 import BeautifulSoup
    from selenium import webdriver
    
    driver = webdriver.Firefox()
    driver.get("https://afltables.com/afl/stats/teams/adelaide/2018_gbg.html")
    
    html = driver.page_source
    soup = BeautifulSoup(html, "lxml")
    
    table = soup.find_all('table', {'id':'sortableTable0'})
    print(table)
    

    有趣的是,页面源在包含表格的div 之前有以下元素:

    <noscript>This page requires Javascript enabled to function<br><br></noscript>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      相关资源
      最近更新 更多