selenium设置chrome浏览器保持登录方式两种options和cookie

方法一:

1.在初始化driver之前先设置options

2.其他关于options介绍链接:http://www.cnblogs.com/baoyu7yi/p/7058537.html

3.代码

from selenium import  webdriver

#实例化谷歌设置选项
option = webdriver.ChromeOptions()
#添加保持登录的数据路径:安装目录一般在C:\Users\黄\AppData\Local\Google\Chrome\User Data
option.add_argument(r"user-data-dir=C:\Users\黄\AppData\Local\Google\Chrome\User Data")

#初始化driver
driver = webdriver.Chrome(options=option)
driver.get("https://ke.qq.com/")
driver.maximize_window()

 方法二:

1.通过F12查找到保存登录的cookie

2.cookie添加的源码解读

  由源码可以看出,添加的cookie是字典类型的。添加键值为name和value,还有其他可选的键。

 这些键名都代表什么意思呢?参考博文《selenium3.7+ python3 添加cookie模拟登陆》,罗列如下

  • name:cookie的名称

  • value:cookie对应的值,动态生成的

  • domain:服务器域名

  • expiry:Cookie有效终止日期

  • path:Path属性定义了Web服务器上哪些路径下的页面可获取服务器设置的Cookie

  • httpOnly:防脚本攻击

  • secure:在Cookie中标记该变量,表明只有当浏览器和Web Server之间的通信协议为加密认证协议时

def add_cookie(self, cookie_dict):
        """
        Adds a cookie to your current session.

        :Args:
         - cookie_dict: A dictionary object, with required keys - "name" and "value";
            optional keys - "path", "domain", "secure", "expiry"

        Usage:
            driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
            driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
            driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure':True})

        """
        self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict})

3.webdriver提供了一些操作cookie的方法。
1)get_cookies():获取所有的cookie信息
2)get_cookie(name):返回字典key为“name”的cookie信息
3)add_cookie(cookie_dict):添加cookie,“cookie_dict”指的是字典对象,必须有key和value
4)delete_cookie(name,optionsString):删除cookie信息。name为要删除的cookie名称,optionsString指该cookie的选项,目前支持的选项包括”路径“和”域“
5)delete_all_cookies():删除所有cookie信息。

4.例:添加一个cookie,保持登录

from selenium import webdriver

'''
1.F12获取cookie,在添加cookie前后都要写上driver.get()
2.此处cookie获取就一个
'''
driver = webdriver.Chrome()
cookie1 = {"name":"_redmine_session","value":"SzByNTJSUXBReEViVUJZd1lLRll4bnFJMW1rRHdiTFVtOXM1ck85M0tiMXB6bWRXOUxoc21leTlWVlFSQ2tHRHVrZS90dTQ0T0pZZmxjQ0dQakRNR2FuMS9keVBXWmdSMEQ3TFJ0T0JHVWlHNEsxMWVZRkdpRFR5amxLbVl5NDZaeWhDRGpHM2M4TzN5VHM4ZTZ4ckV2VWVCbTgrVEFDdVU4YjVOcDNmcHNqYUVjN082YllkUm95YzR4V2dJRkNtZVhTVkVXUHFpRmRXOFRFcXppZHl5UUw5Z1NYUEZYRWRLdTBjZVc3RU5yYz0tLXgzcmcxL2c4ODIzN2hRWnV2QVl3cEE9PQ%3D%3D--3af0df2799ffc8552ef1d9dbf7f5e90379a2ecbd"}
driver.get("http://192.168.129.109/projects/ptts-1-0?jump=account")
driver.add_cookie(cookie_dict=cookie1)
driver.get("http://192.168.129.109/projects/ptts-1-0?jump=account")

5.例:添加两个cookie,保持登录状态(以百度页面登录为例)

driver1 = webdriver.Chrome()
driver1.maximize_window()
cookie2 = {"name":"BDUSS","value":"UJJTH5rcE9qd1VsWDZ5SzFsQkJVZUVPZTMwRi05bzg4UDE5YXJYZDAzNklkRzViQVFBQUFBJCQAAAAAAAAAAAEAAADzdT9HTGlseTAyNTE4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIjnRluI50Zbe"}
cookie3 = {"name":"BAIDUID","value":"F513A1C2ADA0A19C868F711C1792A3D0"}
driver1.get("https://passport.baidu.com/center")
#将获取的两个cookie都添加上
driver1.add_cookie(cookie2)
driver1.add_cookie(cookie3)
driver1.get("https://passport.baidu.com/center")

 

6.在输入以下代码会出现报错为:Message: unable to set cookie。报错信息如下

 

Traceback (most recent call last):
  File "D:/python_workshop/python6/selenium_webdriver/add_cookies的使用(二).py", line 9, in <module>
    driver.add_cookie(cookie_dict=cookies)
  File "D:\Program\python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 872, in add_cookie
    self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
  File "D:\Program\python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "D:\Program\python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unable to set cookie
  (Session info: chrome=66.0.3359.139)
  (Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 6.1.7600 x86_64)

 

 解决方法:参考文档--https://www.cnblogs.com/CoolJayson/p/7421013.html

                需要在driver.add_cookie()前加上driver1.get("url地址")。

               必须首先加载网站,这样Selenium 才能知道cookie 属于哪个网站,即使加载网站的行为对我们没任何用处。如下代码加粗部分。

driver1 = webdriver.Chrome()
driver1.maximize_window()
cookie2 = {"name":"BDUSS","value":"UJJTH5rcE9qd1VsWDZ5SzFsQkJVZUVPZTMwRi05bzg4UDE5YXJYZDAzNklkRzViQVFBQUFBJCQAAAAAAAAAAAEAAADzdT9HTGlseTAyNTE4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIjnRluI50Zbe"}
cookie3 = {"name":"BAIDUID","value":"F513A1C2ADA0A19C868F711C1792A3D0"}
driver1.get("https://passport.baidu.com/center")
#将获取的两个cookie都添加上
driver1.add_cookie(cookie2)
driver1.add_cookie(cookie3)
driver1.get("https://passport.baidu.com/center")

 

posted @ 2018-07-11 22:36  后来的后来  阅读(29023)  评论(2编辑  收藏  举报