我正在尝试使用 Selenium 和 BeautifulSoup 从网页中抓取表格,但我不确定如何使用 BeautifulSoup 获取实际数据。
网页:https://leetify.com/app/match-details/5c438e85-c31c-443a-8257-5872d89e548c/details-general
我尝试提取表行(标记),但是当我调用 find_all 时,数组为空。
当我检查元素时,我看到几个带有 tr 标签的元素,为什么它们不显示在 BeautifulSoup.find_all() ??
我尝试提取表行(标记),但是当我调用 find_all 时,数组为空。
代码:
from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get("https://leetify.com/app/match-details/5c438e85-c31c-443a-8257-5872d89e548c/details-general")
html_source = driver.page_source
soup = BeautifulSoup(html_source, 'html.parser')
table = soup.find_all("tbody")
print(len(table))
for entry in table:
print(entry)
print("\n")
为什么他们不使用 BeautifulSoup.find_all() 出现呢?
快速浏览了一下,页面加载时间似乎很长。
问题是,当您将
driver.page_source
传递给 BeautifulSoup
时,并非所有 HTML/CSS 都会加载。
因此,解决方案是使用显式等待:
等待页面使用 Selenium WebDriver for Python 加载
或者甚至(不太推荐):
from time import sleep
sleep(10)
但我不是 100% 确定,因为我的机器上目前没有安装 Selenium
但是,我想采取完全不同的解决方案:
如果您查看浏览器的网络调用(在浏览器中单击 F12,它将打开开发人员选项),您将看到您要查找的数据(表格)已通过发送
GET
加载
请求他们的 API:
终点位于:
https://api.leetify.com/api/games/5c438e85-c31c-443a-8257-5872d89e548c
您可以直接从浏览器查看。
所以,你可以直接使用
requests
库向上述端点发出GET请求,这样会更高效:
import requests
from pprint import pprint
response = requests.get('https://api.leetify.com/api/games/5c438e85-c31c-443a-8257-5872d89e548c')
data = response.json()
pprint(data)
打印(截断):
{'agents': [{'gameFinishedAt': '2024-07-06T07:10:02.000Z',
'gameId': '5c438e85-c31c-443a-8257-5872d89e548c',
'id': '63e38340-d1ae-4e19-b51c-e278e3325bbb',
'model': 'customplayer_tm_balkan_variantk',
'steam64Id': '76561198062922849',
'teamNumber': 2},
{'gameFinishedAt': '2024-07-06T07:10:02.000Z',
'gameId': '5c438e85-c31c-443a-8257-5872d89e548c',
'id': 'e10f9fc4-759d-493b-a17f-a85db2fcd09d',
'model': 'customplayer_ctm_fbi_variantg',
'steam64Id': '76561198062922849',
'teamNumber': 3},
这种方法无需等待页面加载,让您可以直接访问数据。