我要解析的这个页面 - 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 是“第二个”表的 ID。它不会给我一个错误,也不会返回任何东西。它是空的。
最佳答案
既然第二张表是动态生成的,为什么不结合selenium
, BeautifulSoup
, 和 pandas
得到你想要的?
例如:
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
文件,嗯,看起来像你想要的那个表。 :)关于python - 在 BeautifulSoup 中索引多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64751900/