如何使用 Selenium 正确发出 Fetch 请求

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

我需要使用 Python 使用 Selenium 制作一个具有自定义 HTTP 标头的特定 http 请求(GET 或 POST),并将响应 JSON 返回到 Python 中。浏览器应该通过代理服务器。

我发现最准确的方法是发出正确格式的 JS 获取请求。

我尝试过以下方法:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


proxy_server_url = "127.0.0.1:8888"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy_server_url)
chrome_options.add_argument("ignore-certificate-errors")

chrome = webdriver.Chrome(options=chrome_options)

chrome.get("https://myhttpheader.com/")

print(chrome.execute_script("fetch('https://myhttpheader.com/', {headers: {'Accept': '*/*','Accept-Language': 'ru,en-US;q=0.9,en;q=0.8,ru-RU;q=0.7','Cache-Control': 'no-cache','Connection': 'keep-alive','Origin': 'https://myhttpheader.com','Pragma': 'no-cache','Referer': 'https://myhttpheader.com/','Sec-Fetch-Dest': 'empty','Sec-Fetch-Mode': 'cors','Sec-Fetch-Site': 'cross-site','CUSTOM_HEADER_1': 'value_1','CUSTOM_HEADER_2': 'value_2' }})"))

chrome.quit()

有几个问题:

  1. 这样的 fetch 请求返回 Promise。我可以通过
    fetch(...).then(response=>response.json()).then(data=>{ console.log(data); })
    在控制台手动查看返回的数据,但是如何通过selenium在python中访问它?
  2. 我在代理服务器上没有看到任何请求,因此它忽略代理设置。代理设置有什么问题?
javascript python selenium-webdriver fetch
1个回答
0
投票

Fetch 是异步的,所以使用execute_async_script :

html = driver.execute_async_script('''
  let callback = arguments[0]
  fetch("https://somwurl", {
    headers: { /* headers go here */ }.
    method: "GET", // or POST
    body: "" //  for POST only
  }).then(r => r.text()).then(callback)
''')
© www.soinside.com 2019 - 2024. All rights reserved.