Selenium的cookie如何requests使用
时间: 2024-11-24 10:44:04 浏览: 23
在Selenium中,我们使用`webdriver`对象的`add_cookie`方法来设置浏览器的cookies。而当需要使用requests库时,cookies通常是以字典的形式存储的,可以直接传递给requests的`headers`参数。
以下是将Selenium的cookies转换为requests使用的步骤:
1. **获取Selenium cookies**:
```python
def get_selenium_cookies(driver):
cookies_list = driver.get_cookies()
selenium_cookies = [{'name': c['name'], 'value': c['value']} for c in cookies_list]
return selenium_cookies
```
2. **将Selenium cookies转换为requests格式**:
```python
def convert_selenium_cookies_to_requests(selenium_cookies):
requests_cookies = {cookie['name']: cookie['value'] for cookie in selenium_cookies}
return requests_cookies
```
3. **在requests中使用转换后的cookies**:
```python
def access_url_with_requests(url, selenium_cookies_path):
with open(selenium_cookies_path, 'r', encoding='utf8') as f:
selenium_cookies = get_selenium_cookies(json.load(f))
requests_cookies = convert_selenium_cookies_to_requests(selenium_cookies)
response = requests.get(url, cookies=requests_cookies)
```
4. **调用函数并发送请求**:
```python
if __name__ == '__main__':
# 示例中的cookies保存路径
selenium_cookies_path = 'QQ空间_cookies.txt'
access_url_with_requests('https://dnf.qq.com/gift.shtml', selenium_cookies_path)
```
在这个例子中,`access_url_with_requests`函数会读取Selenium cookies,然后使用它们去发送GET请求。
阅读全文