python+selenium利用cookie记住密码

先上代码

 1 from selenium import webdriver
 2 from time import sleep
 3 
 4 dr = webdriver.Chrome()
 5 dr.get("https://www.cnblogs.com/")
#导入cookie
6 cookies =[ 7 { 8 "domain": ".cnblogs.com", 9 "expirationDate": 1640700103, 10 11 "name": "_ga", 12 "path": "/", 13 "sameSite": "unspecified", 14 15 "storeId": "0", 16 "value": "GA1.2.1994841149.1573968390", 17 "id": 1 18 }, 19 { 20 "domain": ".cnblogs.com", 21 "expirationDate": 1577714503, 22 23 "name": "_gid", 24 "path": "/", 25 "sameSite": "unspecified", 26 27 "storeId": "0", 28 "value": "GA1.2.1593168612.1577458373", 29 "id": 2 30 }, 31 { 32 "domain": ".cnblogs.com", 33 "expirationDate": 1578313746, 34 35 "name": ".Cnblogs.AspNetCore.Cookies", 36 "path": "/", 37 "sameSite": "unspecified", 38 39 "storeId": "0", 40 "value": "CfDJ8FKe-Oc4rmBCjdz4t-OOIu1Y1_q7IgBvpSWg9ZdbcQRv1kjbdhbKEb1bbQcymHdhZggWPZJEzu6knlhtVRoL5gm98aOUkvGCdVENhnai_GifETOTpe_SxXNOUkL64n9v-5_-GNkGTzopC2OoI_IrwBEMEqMKuXHaKI5BOsQ0_yHeKc0hoBSsBcBz-c00SSEhvitkti2-1BnYLpmuRLQWU7H2opv8RXRTHXXaEcnzgz1uSiL2Os2yNvuXmARD2Xc1Ies1vl1bLZxO6PFcyoPksROP9GYjP9381OjJteQJuUFNIfEz5MgFMyzznCm-dOUO-xnuJclWWBO3wBQITjSUmd4FTaoyNoNuTzxzJMsqcPXRQvx7Yw1awxvu5DgYsXJrlGXA-ImmAPkCqOta7W-hmnT0DtcjtDmN6VDeRnanr3QgjWD4-Bas4HNzwgbxSmudp0dNs4Ob20BVz8akayy-U6pOUyGQkRl5mbCKH88iv0-KswFcqWBu8L8bB9w36r95T6Mab1q4xiIuWyKFCKyVv-1_PNzdFMlIp-_l-DMNTLMl-AuZMOdzIbeaAhoLpKKUOQ", 41 "id": 3 42 }, 43 { 44 "domain": ".cnblogs.com", 45 "expirationDate": 1577665580, 46 47 "name": ".CNBlogsCookie", 48 "path": "/", 49 "sameSite": "unspecified", 50 51 "storeId": "0", 52 "value": "3F4C2E41FB84510397F7713E24634AE137F7F6EC0345FC2B52852EE471C4FA40319845DB63DE7126C8D4D0B3AF1F60A89ADDF8A91230076D478DD64FC11782626974087631363125C12A34325A15627EC2B5F5E7", 53 "id": 4 54 }, 55 { 56 "domain": "www.cnblogs.com", 57 "expirationDate": 1892984163, 58 59 "name": "_dx_uzZo5y", 60 "path": "/", 61 "sameSite": "unspecified", 62 63 "storeId": "0", 64 "value": "a0e3626a4cbee8ec2e131c2708e2e53af902a37e26f1365f06ae70c513e313920716cf88", 65 "id": 5 66 } 67 ] 68 69 for cook in cookies: 70 dr.add_cookie(cook) 71 72 dr.refresh()#刷新浏览器

代码中的cookie如何生成的呢?

利用cookie复制工具复制所有的cookie

 

 不过需要注意的是全部复制出来的会报false或者true未定义,只需要将的未定义的false或者true的那一行删除掉或者改成首字母大写。

如果出现以下错误:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid 'sameSite'
  (Session info: chrome=80.0.3987.106)

解决方案:

直接遍历pop掉sameSite参数即可。这样添加就不会报错

或者最后一段代码改成:

1 for cook in cookies:
2     #遍历删除sameSite,注意,旧版chrome可能是没有samesite
3     try:
4         cook.pop('sameSite')
5     except:
6         pass
7     dr.add_cookie(cook)
8 dr.refresh()

 

posted @ 2019-12-29 22:57  Harry_666  阅读(1060)  评论(0编辑  收藏  举报