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

来源:互联网 发布:淘宝做客服考试答案 编辑:程序博客网 时间:2024/06/15 16:51
# python3import requestsimport osimport sqlite3from win32crypt import CryptUnprotectData# cookies存放路径cookie_path = os.environ['LOCALAPPDATA'] + r"\Google\Chrome\User Data\Default\Cookies"# 获取cookiedef 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# 获取所有hostsdef 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 hostsheaders = {            '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'                         # 设定测试urltest_host = '.baidu.com'                                # 设定测试hosttest_cookies = get_cookie_from_chrome(test_host)        # 获取测试host的cookiesuser_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

原创粉丝点击