添加适用于 Firefox Webdriver 但不适用于 PhantomJS 的 Cookie

2024-03-23

我有一个带有饼干的泡菜,是通过以下命令创建的

def doLogin(driver):
    #do login stuff
    pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))

我有获取 cookie 的示例代码

driver = webdriver.PhantomJS()
self.doLogin(driver)
driver.delete_all_cookies()
for cookie in pickle.load(open("cookies.pkl", "rb")):
    driver.add_cookie(cookie)

我可以看到它很好地创建了cookie,因为如果我print没关系,add_cookie() 正在做一些见不得人的事情

这给出了以下异常

WebDriverException:消息:{“errorMessage”:“无法设置 Cookie","re​​quest":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"219" ,"Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:50738","User-Agent":"Python-urllib/2.7"},"httpVersion": "1.1","method":"POST","post":"{\"sessionId\": \“391db430-154a-11e6-8a0a-ef59204729f5 \”,\“cookie \”:{\“域\”: \“秘密网站\”,\“名称\”:\“JSESSIONID \”,\“值\”: \"8332B6099FA3BBBC82893D4C7E6E918B\", \"路径\": \"也是一个秘密\", “httponly”:假,“安全”: true}}","url":"/cookie","urlParsed":{"anchor":"","查询":"","文件":"cookie","目录":"/","路径":"/cookie","相对":"/cookie","端口":"","主机":"","密码":"","用户":"","userInfo":" ","authority":"","protocol":"","source":"/cookie","queryKey":{},"chunks":["cookie"]},"urlOriginal":"/session /391db430-154a-11e6-8a0a-ef59204729f5/cookie"}} 屏幕截图:可通过屏幕查看

为了工作,我需要将 webdriver 更改为 Firefox

这是一个已知的 PhantomJS 问题吗?


PhantomJS 驱动程序似乎不支持某些键/值。 为了解决这个问题,我将注入最重要的execute_script:

def save_cookies(driver, file_path):
    LINE = "document.cookie = '{name}={value}; path={path}; domain={domain}; expires={expires}';\n"
    with open(file_path, 'w') as file :
        for cookie in driver.get_cookies() :
            file.write(LINE.format(**cookie))

def load_cookies(driver, file_path):
    with open(file_path, 'r') as file:
        driver.execute_script(file.read())


from selenium import webdriver

driver = webdriver.PhantomJS()

# load the domain
driver.get("https://stackoverflow.com/users/login")

# save the cookies to a file
save_cookies(driver, r"cookies.js")

# delete all the cookies
driver.delete_all_cookies()

# load the cookies from the file
load_cookies(driver, r"cookies.js")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

添加适用于 Firefox Webdriver 但不适用于 PhantomJS 的 Cookie 的相关文章

随机推荐