首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在使用Python3、Selenium Chrome WebDriver进行第一次请求之前预加载cookie?

问如何在使用Python3、Selenium Chrome WebDriver进行第一次请求之前预加载cookie?
EN

Stack Overflow用户
提问于 2020-08-02 19:33:19
回答 1查看 3.6K关注 0票数 3

在使用add_cookie()对域stackoverflow.com上的页面执行实际请求之前,可以使用stackoverflow.com在Selenium Chrome WebDriver中为域添加cookie吗?

在尝试时:

代码语言:javascript
复制
driver.webdriver.add_cookie({'name' : 'testcookie', 'value' : 'testvalue', 'domain' : 'stackoverflow.com'})
driver.webdriver.get('https://stackoverflow.com/')

我得到“您只能为当前域设置cookie”。

我想说的是,我看到并尝试了一些避免问题而不是解决问题的解决方案,比如在添加cookie之前,先访问域上的404页,在Selenium中创建“域槽”,但是虽然这些解决方案允许添加cookie,但它们仍然需要额外的请求并与站点联系,同时没有设置cookie。

在处理CAPTCHA系统和一些非常具体的WAFs时,这是一个问题,这些WAFs不愿意连续地看到没有cookie的请求,而另一个带有cookies的请求只有在经过登录过程之后才会有。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-02 19:33:19

从Chrome 64开始,我们现在可以访问Chrome DevTools协议v1.3,它允许通过Network.setCookie方法将cookie设置到任何域,从而消除了预先设置域所需的额外get调用。

例如Python3

代码语言:javascript
复制
import os.path
import pickle
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def save_cookies():
    print("Saving cookies in " + selenium_cookie_file)
    pickle.dump(driver.get_cookies() , open(selenium_cookie_file,"wb"))

def load_cookies():
    if os.path.exists(selenium_cookie_file) and os.path.isfile(selenium_cookie_file):
        print("Loading cookies from " + selenium_cookie_file)
        cookies = pickle.load(open(selenium_cookie_file, "rb"))

        # Enables network tracking so we may use Network.setCookie method
        driver.execute_cdp_cmd('Network.enable', {})

        # Iterate through pickle dict and add all the cookies
        for cookie in cookies:
            # Fix issue Chrome exports 'expiry' key but expects 'expire' on import
            if 'expiry' in cookie:
                cookie['expires'] = cookie['expiry']
                del cookie['expiry']

            # Replace domain 'apple.com' with 'microsoft.com' cookies
            cookie['domain'] = cookie['domain'].replace('apple.com', 'microsoft.com')

            # Set the actual cookie
            driver.execute_cdp_cmd('Network.setCookie', cookie)

        # Disable network tracking
        driver.execute_cdp_cmd('Network.disable', {})
        return 1

    print("Cookie file " + selenium_cookie_file + " does not exist.")
    return 0

def pretty_print(pdict):
    for p in pdict:
        print(str(p))
    print('',end = "\n\n")


# Minimal settings
selenium_cookie_file = '/home/selenium/test.txt'

browser_options = Options()
browser_options.add_argument("--headless")

# Open a driver, get a page, save cookies
driver = webdriver.Chrome(chrome_options=browser_options)
driver.get('https://apple.com/')
save_cookies()
pretty_print(driver.get_cookies())


# Rewrite driver with a new one, load and set cookies before any requests
driver = webdriver.Chrome(chrome_options=browser_options)
load_cookies()
driver.get('https://microsoft.com')
pretty_print(driver.get_cookies())

您将在上面看到,我们通过一个请求从域'apple.com‘获得cookies,并在实际向'microsoft.com’发出请求之前将其加载并设置为域'microsoft.com‘。

只要将变量selenium_cookie_file设置为有效的可写文件路径,代码就会被测试和工作。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63220248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档