我需要使用 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()
有几个问题:
fetch(...).then(response=>response.json()).then(data=>{ console.log(data); })
在控制台手动查看返回的数据,但是如何通过selenium在python中访问它?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)
''')