我想解析的这个页面- https://fbref.com/en/comps/9/gca/Premier-League-Stats
它有两个表,我试图从第二个表中获取信息,但是每次运行这段代码时,它都会显示第一个表。
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。
它没有给我一个错误,也没有返回任何东西。它是空的。
发布于 2020-11-09 11:30:21
既然第二个表是动态生成的,那么为什么不结合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
文件,看起来就像你想要的那个表。:)
发布于 2020-11-09 10:56:13
您在检查元素时看到的HTML是使用Javascript生成的。但是,在原始html中不能使用脚本获得相同的类。我禁用了这个站点的Javascript,我发现表是不可见的。
您可以尝试类似于Selenium之类的东西。this问题中有很好的信息。
https://stackoverflow.com/questions/64751900
复制