selenium 提取谷歌游览器Cookie的五种方法

纯手动提取谷歌游览器cookie

方法就是先F12打开开发者工具,然后访问要提取cookie的网站,然后在网络中选中刚才访问的请求,然后在请求头中找到cookie这一项,复制对应的值即可。
将请求以curl命令形式复制到剪切板之后,我们就可以通过代码直接提取cookie,代码如下:

import re
import pyperclip


def extractCookieByCurlCmd(curl_cmd):
    cookie_obj = re.search("-H \$?'cookie: ([^']+)'", curl_cmd, re.I)
    if cookie_obj:
        return cookie_obj.group(1)


cookie = extractCookieByCurlCmd(pyperclip.paste())
print(cookie)

selenium手动登录并获取cookie

以保存B站登录cookie为例:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import time
import json

browser = webdriver.Chrome()
browser.get("https://passport.bilibili.com/login")
flag = True
print("等待登录...")
while flag:
    try:
        browser.find_element(By.XPATH,
                             "//div[@class='user-con signin']|//ul[@class='right-entry']"
                             "//a[@class='header-entry-avatar']")
        flag = False
    except NoSuchElementException as e:
        time.sleep(3)
print("已登录,现在为您保存cookie...")
with open('cookie.txt', 'w', encoding='u8') as f:
    json.dump(browser.get_cookies(), f)
browser.close()
print("cookie保存完成,游览器已自动退出...")

selenium无头模式获取非登录cookie

比如抖音这种网站想下载其中的视频,就必须要带有一个初始的cookie,但这个cookie生成的算法比较复杂,纯requests很难模拟,这时我们完全可以借助selenium来加载网页并获取cookie节省分析js的时间。
代码如下:

from selenium import webdriver
import time


def selenium_get_cookies(url='https://www.douyin.com'):
    """无头模式提取目标链接对应的cookie,代码作者:小小明-代码实体"""
    start_time = time.time()
    option = webdriver.ChromeOptions()
    option.add_argument("--headless")
    option.add_experimental_option('excludeSwitches', ['enable-automation'])
    option.add_experimental_option('useAutomationExtension', False)
    option.add_argument(
        'user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')
    option.add_argument("--disable-blink-features=AutomationControlled")
    print("打开无头游览器...")
    browser = webdriver.Chrome(options=option)
    print(f"访问{url} ...")
    browser.get(url)
    cookie_list = browser.get_cookies()
    # 关闭浏览器
    browser.close()
    cost_time = time.time() - start_time
    print(f"无头游览器获取cookie耗时:{cost_time:0.2f} 秒")
    return {row["name"]: row["value"] for row in cookie_list}


print(selenium_get_cookies("https://www.douyin.com"))

打印结果如下:

打开无头游览器...
访问https://www.douyin.com ...
无头游览器获取cookie耗时:3.28{'': 'douyin.com', 'ttwid': '1%7CZn_LJdPjHKdCy4jtBoYWL_yT3NMn7OZVTBStEzoLoQg%7C1642932056%7C80dbf668fd283c71f9aee1a277cb35f597a8453a3159805c92dfee338e70b640', 'AB_LOGIN_GUIDE_TIMESTAMP': '1642932057106', 'MONITOR_WEB_ID': '651d9eca-f155-494b-a945-b8758ae948fb', 'ttcid': 'ea2b5aed3bb349219f7120c53dc844a033', 'home_can_add_dy_2_desktop': '0', '_tea_utm_cache_6383': 'undefined', '__ac_signature': '_02B4Z6wo00f01kI39JwAAIDBnlvrNDKInu5CB.AAAPFv24', 'MONITOR_DEVICE_ID': '25d4799c-1d29-40e9-ab2b-3cc056b09a02', '__ac_nonce': '061ed27580066860ebc87'}

获取本地谷歌游览器中的cookie

只要我们使用debug远程调试模式运行本地的谷歌游览器,再用selenium控制即可提取之前登录的cookie:

import os
import winreg
from selenium import webdriver
import time


def get_local_ChromeCookies(url, chrome_path=None):
    """提取本地谷歌游览器目标链接对应的cookie,代码作者:小小明-代码实体"""
    if chrome_path is None:
        key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"ChromeHTML\Application")
        path = winreg.QueryValueEx(key, "ApplicationIcon")[0]
        chrome_path = path[:path.rfind(",")]
    start_time = time.time()
    command = f'"{chrome_path}" --remote-debugging-port=9222'
    # print(command)
    os.popen(command)
    option = webdriver.ChromeOptions()
    option.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    browser = webdriver.Chrome(options=option)
    print(f"访问{url}...")
    browser.get(url)
    cookie_list = browser.get_cookies()
    # 关闭浏览器
    browser.close()
    cost_time = time.time() - start_time
    print(f"获取谷歌游览器cookie耗时:{cost_time:0.2f} 秒")
    return {row["name"]: row["value"] for row in cookie_list}


print(get_local_ChromeCookies("https://www.douyin.com"))

谷歌游览器的启动参数加上 --remote-debugging-port=9222即可开启远程debug模式,而selenium则可以通过debuggerAddress参数连接一个现有开启远程debug模式的谷歌游览器。

直接解密cookies文件

代码块

"""
小小明的代码
CSDN主页:https://blog.csdn.net/as604049322
"""
__author__ = '小小明'
__time__ = '2022/1/23'

import base64
import json
import os
import sqlite3

import win32crypt
from cryptography.hazmat.primitives.ciphers.aead import AESGCM


def load_local_key(localStateFilePath):
    "读取chrome保存在json文件中的key再进行base64解码和DPAPI解密得到真实的AESGCM key"
    with open(localStateFilePath, encoding='u8') as f:
        encrypted_key = json.load(f)['os_crypt']['encrypted_key']
    encrypted_key_with_header = base64.b64decode(encrypted_key)
    encrypted_key = encrypted_key_with_header[5:]
    key = win32crypt.CryptUnprotectData(encrypted_key, None, None, None, 0)[1]
    return key


def decrypt_value(key, data):
    "AESGCM解密"
    nonce, cipherbytes = data[3:15], data[15:]
    aesgcm = AESGCM(key)
    plaintext = aesgcm.decrypt(nonce, cipherbytes, None).decode('u8')
    return plaintext


def fetch_host_cookie(host):
    "获取指定域名下的所有cookie"
    userDataDir = os.environ['LOCALAPPDATA'] + r'\Google\Chrome\User Data'
    localStateFilePath = userDataDir + r'\Local State'
    cookiepath = userDataDir + r'\Default\Cookies'
    # 97版本已经将Cookies移动到Network目录下
    if not os.path.exists(cookiepath) or os.stat(cookiepath).st_size == 0:
        cookiepath = userDataDir + r'\Default\Network\Cookies'
    # print(cookiepath)
    sql = f"select name,encrypted_value from cookies where host_key like '%.{host}'"
    cookies = {}
    key = load_local_key(localStateFilePath)
    with sqlite3.connect(cookiepath) as conn:
        cu = conn.cursor()
        for name, encrypted_value in cu.execute(sql).fetchall():
            cookies[name] = decrypt_value(key, encrypted_value)
    return cookies


if __name__ == '__main__':
    print(fetch_host_cookie("douyin.com"))
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
selenium是一个自动化测试工具,用于模拟用户操作浏览器。如果在使用selenium时遇到谷歌浏览器闪退的情况,可能是以下几个原因: 1. 谷歌浏览器版本不兼容:selenium谷歌浏览器的兼容性有要求,如果所使用的selenium版本不适配当前谷歌浏览器版本,则可能导致闪退。建议尝试更新selenium到最新版本,或使用与谷歌浏览器版本兼容的selenium版本。 2. 谷歌浏览器驱动问题:使用selenium需要依赖于谷歌浏览器驱动,如果驱动版本不匹配或者驱动文件缺失,可能导致谷歌浏览器闪退。建议检查驱动版本与谷歌浏览器版本是否对应,并确保驱动文件存在于正确的路径下。 3. 系统环境问题:某些时候,谷歌浏览器闪退可能与操作系统环境相关。可能是由于操作系统或其他软件的冲突导致的。建议检查并更新操作系统、谷歌浏览器和相关软件的版本,或尝试在其他操作系统上运行selenium。 4. 代码问题:selenium使用不正确或者代码逻辑有误也可能导致谷歌浏览器闪退。建议检查代码中是否存在错误,例如在使用浏览器窗口时是否有合适的等待时间、是否使用了正确的定位方式、是否正确处理弹窗等。 总之,解决selenium打开谷歌浏览器闪退的问题需要综合考虑以上几个方面。根据具体情况进行排查和处理,可能需要更新软件版本、检查驱动、排除冲突等操作来解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值