我需要 Selenium WebDriver Firefox 返回与使用请求相同的响应,有什么办法吗?

问题描述 投票:0回答:1

我已经组装了所有代码来处理此响应:

response = requests.get(url).text
soup = BeautifulSoup(response, 'html.parser')

但是我需要使用

Selenium WebDriver
而不是
requests
,我尝试这样使用它:

driver = web_driver()
response = driver.page_source
soup = BeautifulSoup(response, 'html.parser')

但是响应不同,这会在代码中产生一些错误。有没有办法让

Selenium WebDriver
收集与使用
requests
完全相同的响应?

细节:如果可能的话,有一种方法可以始终获得相同的结果,无论使用什么

url

使用示例

在一个场景中,我想创建一个 pandas 数据框,其中包含此 url 中存在的该表的确切值。

requests
在阅读元素方面提供与
Selenium
不同的结果。

https://int.soccerway.com/teams/egypt/pharco/38185/squad/

enter image description here

python selenium-webdriver python-requests selenium-firefoxdriver
1个回答
0
投票

以下是如何从 api 获取表(通过检查网络选项卡找到):

import requests
from bs4 import BeautifulSoup
import pandas as pd 


url = 'https://int.soccerway.com/a/block_team_squad'
params = {
    'block_id': 'page_team_1_block_team_squad_7',
    'callback_params': '{"team_id":"38185"}',
    'action': 'changeSquadSeason',
    'params': '{"season_id":"23909"}',
}

headers = {
    'x-requested-with': 'XMLHttpRequest',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
}

response = requests.get(url, headers=headers, params=params)
html = response.json()['commands'][0]['parameters']['content']
table = BeautifulSoup(html, 'html.parser')

# class selectors for the columns we want to keep
selectors = [
    'shirtnumber', 
    'name', 
    'age', 
    'position', 
    'game-minutes', 
    'appearances',
    'lineups',
    'subs-in',
    'subs-out',
    'subs-on-bench',
    'goals',
    'assists',
    'yellow-cards',
    '2nd-yellow-cards',
    'red-cards'
]


# dynamically add column names
# alternatively you can use a static list or the selectors themselves
head = []
for selector in selectors:
    th = table.thead.find('th', {'class': selector})
    if txt := th.get_text(strip=True):
        head.append(txt)
    elif th.img:
        head.append(th.img['title'])
    else:
        head.append(selector.capitalize())


# creating the dataframe
rows = [[td.text for td in tr.find_all('td', {'class': selectors})] for tr in table.tbody.find_all('tr')]
df = pd.DataFrame(rows, columns=head)

由于某些列名称是文本,其他列名称是图像,因此我使用“标题”属性或类名称代替。您可以跳过该步骤并使用

pd.read_html()
将表加载到数据框中,但结果不会包含所有标题名称和空列(照片/标志)。

© www.soinside.com 2019 - 2024. All rights reserved.