使用本地cookie缓存,模拟访问

本文介绍了如何利用Python结合本地Chrome浏览器的Cookie信息,进行模拟访问网站的操作。通过解析Cookie,实现更真实的网络请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# python3
import requests
import os
import sqlite3
from win32crypt import CryptUnprotectData

# cookies存放路径
cookie_path = os.environ['LOCALAPPDATA'] + r"\Google\Chrome\User Data\Default\Cookies"

# 获取cookie
def get_cookie_from_chrome(host=None):
    sql = "select host_key,name,encrypted_value from cookies where host_key='{}'".format(host)
    with sqlite3.connect(cookie_path) as conn:
        cursor = conn.cursor()
        cookies = { name: CryptUnprotectData(encrypted_value)[1].decode() 
                     for host_key, name, encrypted_value in cursor.execute(sql).fetchall() }
        return cookies

# 获取所有hosts
def get_hosts():
    sql = "select host_key from cookies"
    with sqlite3.connect(cookie_path) as conn:
        cursor = conn.cursor()
        hosts = set(cursor.execute(sql).fetchall())
    return hosts

headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
        }


test_url = 'http://i.baidu.com'                         # 设定测试url
test_host = '.baidu.com'                                # 设定测试host
test_cookies = get_cookie_from_chrome(test_host)        # 获取测试host的cookies
user_name = "那******晴"

if __name__ == "__main__" :
    # 使用get请求访问测试url
    resp = requests.get(
            url = test_url,
            headers = headers,
            cookies = test_cookies,
            allow_redirects = 1
            )

    # 保存到txt中查看是否访问成功
    with open('test.txt', 'w', encoding='utf-8') as f:
        f.write(resp.text)

    # 检查是否登录成功
    assert user_name in resp.text, '使用cookie模拟访问失败'

# 备注:其中test_url, test_host, user_name需要替换,替换完成后可以直接运行

参考地址:http://www.cnblogs.com/gayhub/p/pythongetcookiefromchrome.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值