【问题标题】:Indexing multiple tables in BeautfulSoup在 BeautifulSoup 中索引多个表
【发布时间】:2021-02-21 09:18:18
【问题描述】:

我要解析的这个页面 - https://fbref.com/en/comps/9/gca/Premier-League-Stats

它有 2 个表,我试图从第二个表中获取信息,但每次运行此代码时它都会显示第一个表。

from bs4 import BeautifulSoup
import requests

source = requests.get('https://fbref.com/en/comps/9/gca/Premier-League-Stats').text
soup = BeautifulSoup(source, 'lxml')
stattable = soup.find('table', class_= 'min_width sortable stats_table min_width shade_zero')[1]

print(stattable)

min_width sortable stats_table min_width shade_zero 是'second'表的ID。

它不会给我一个错误,也不会返回任何东西。它是空的。

【问题讨论】:

    标签: python html matplotlib beautifulsoup data-science


    【解决方案1】:

    既然第二张表是动态生成的,何不将seleniumBeautifulSouppandas组合起来得到你想要的呢?

    例如:

    import time
    
    import pandas as pd
    from bs4 import BeautifulSoup
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.headless = False
    driver = webdriver.Chrome(options=options)
    
    driver.get("https://fbref.com/en/comps/9/gca/Premier-League-Stats")
    time.sleep(2)
    
    soup = BeautifulSoup(driver.page_source, "html.parser").find("div", {"id": "div_stats_gca"})
    driver.close()
    
    df = pd.read_html(str(soup), skiprows=[0, 1])
    df = pd.concat(df)
    df.to_csv("data.csv", index=False)
    
    

    这会输出一个.csv 文件,嗯,看起来就像你想要的那个表。 :)

    【讨论】:

      【解决方案2】:

      您在检查元素时看到的 HTML 是使用 Javascript 生成的。但是,您使用脚本获得的原始 html 中没有相同的类。 我为此站点禁用了 Javascript,但我看到该表不可见。
      您可以尝试 Selenium 之类的方法。 this问题中有很好的信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-20
        • 2019-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多