python - 在 BeautifulSoup 中索引多个表

标签 python html matplotlib beautifulsoup data-science

我要解析的这个页面 - 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文件,嗯,看起来像你想要的那个表。 :)
enter image description here

关于python - 在 BeautifulSoup 中索引多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64751900/

相关文章:

Python:找到3个相邻的列表项并确定其中第一个的列表索引

python - 无法使用 matplotlib 正确导出为 svg 和 pdf

javascript - 删除输入元素的焦点以便可以使用箭头键滚动页面?

python-3.x - 图中的 Axis 隐藏了 Axis 标签?

python - 如何在 Matplotlib 中与线程一起执行动画?

python - RandomForestRegressor 导致 KeyError : 'squared_error'

python - 了解tensorflow中的设备分配、并行性(tf.while_loop)和tf.function

PHP 到 jquery dialog() 交互问题。

php - jquery 通过 php echo 命令返回值

pandas - 使用日期时间列类型设置主要 Xtick