Selenium 设置请求头
时间: 2024-11-16 12:13:32 浏览: 34
Selenium是一个流行的自动化测试工具,它可以模拟浏览器行为,包括发送HTTP请求。为了设置请求头,你需要使用`webdriver.FirefoxProfile`(对于Firefox)、`options.add_argument()`(对Chrome),或者是`DesiredCapabilities`(适用于多种浏览器)。下面是一个简单的例子,展示如何在Python的Selenium中设置请求头:
```python
from selenium import webdriver
# 创建一个FirefoxProfile对象
profile = webdriver.FirefoxProfile()
# 添加自定义请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
profile.set_preference('http.headers.useragent', headers['User-Agent'])
# 使用这个配置创建一个新的Firefox实例
driver = webdriver.Firefox(firefox_profile=profile)
# 现在每次打开新页面,都会带有我们设置的请求头
driver.get('https://example.com')
# 关闭驱动
driver.quit()
```
阅读全文
相关推荐

















