python - 抓取时无法识别表格
问题描述
初学者问题.. 我正在尝试从表中抓取数据,但我似乎无法识别它,我尝试使用类和 id 来识别它,但我的结果是 0。代码和输出如下。
# Import necessary packages
from bs4 import BeautifulSoup
import requests
import pandas as pd
import re
# Site URL
url="https://fbref.com/en/comps/9/stats/Premier-League-Stats"
# Make a GET request to fetch the raw HTML content
html_content = requests.get(url).text
# Parse HTML code for the entire site
soup = BeautifulSoup(html_content, "lxml")
#print(soup.prettify()) # print the parsed data of html
gdp = soup.find_all("table", attrs={"id": "stats_standard"})
print("Number of tables on site: ",len(gdp))
Output - 'Number of tables on site: 0'
解决方案
我建议你使用 selenium 进行这种刮,它的性能非常可靠。
此代码将为您工作:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
option = Options()
option.add_argument('--headless')
url = 'https://fbref.com/en/comps/9/stats/Premier-League-Stats'
driver = webdriver.Chrome(options=option)
driver.get(url)
bs = BeautifulSoup(driver.page_source, 'html.parser')
gdp = bs.find_all('table', {'id': 'stats_standard'})
driver.quit()
print("Number of tables on site: ",len(gdp))
输出
Number of tables on site: 1
推荐阅读
- dart - 关闭应用程序时删除共享首选项
- spring - 如何从另一个 Rest Controller 调用 Rest Controller
- elasticsearch - 没有通配符星号的 Elastic Search 查询
- amazon-web-services - EC2。负载均衡器。必须至少指定两个子网
- mysql - MySQL - 从具有参考 ID 的行中查找值
- java - 如何保存在函数内部进行的数组更改?
- swift4 - 为什么不在子对象上调用 KVO 观察者?
- c# - c#许多异步HttpWebRequest
- aurelia - Aurelia 要求奇怪的...xxxHTMLLINKxxx...文件,它永远不存在
- bash - 在行尾删除可变数量的重复字符