用谷歌浏览器自动化测试H5页面跨域(CORS error)的解决方法

 CORS (Cross-Origin Resource Sharing) 错误通常发生在浏览器中,当你尝试从一个域名访问另一个域名的资源时。在Python自动化测试或爬虫中遇到CORS错误时,可以尝试以下几种解决方案

1. 使用Selenium时添加参数绕过CORS

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--disable-web-security') # 禁用同源策略
options.add_argument('--user-data-dir=/path/to/profile') # 有时需要指定用户目录

driver = webdriver.Chrome(options=options)

2. 使用requests库时添加合适的请求头
import requests

headers = {
'User-Agent': 'Mozilla/5.0',
'Origin': 'https://example.com', # 设置合适的Origin
'Referer': 'https://example.com/login',
}

response = requests.post('https://api.example.com/login', headers=headers, data=payload)

3. 如果是API请求,尝试添加CORS相关头
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
}

4. 使用代理服务器
proxies = {
'http': 'http://your-proxy-address:port',
'https': 'https://your-proxy-address:port'
}

requests.get('https://target-site.com', proxies=proxies)

5. 对于H5页面,可能需要处理预检请求(OPTIONS)
# 首先发送OPTIONS请求
options_response = requests.options(
'https://api.example.com/login',
headers={
'Access-Control-Request-Method': 'POST',
'Access-Control-Request-Headers': 'Content-Type'
}
)

# 然后发送实际请求
if options_response.status_code == 200:
response = requests.post('https://api.example.com/login', data=payload)

posted @ 2025-04-29 09:50  娜乌西卡在路上  阅读(226)  评论(0)    收藏  举报