selinium中新增cookies的方法 python
阿新 • • 發佈:2018-12-20
driver = webdriver.Chrome() driver.get('https://www.tianyancha.com/company/256283648') cookies = { 'TYCID': '71b12660d7f311e880d78365f0abdc98', 'undefined': '71b12660d7f311e880d78365f0abdc98', 'ssuid': '4887198200', '_ga': 'GA1.2.768229795.1540430128', 'Hm_lvt_e92c8d65d92d534b0fc290df538b4758': '1541471290,1541554579,1541587929,1541588890', 'aliyungf_tc': 'AQAAAOJGQFKR+wQALcoFcGA/NZPpSYh/', 'csrfToken': 'OL7DSne1tpq4IiRqC5M-N3f1', 'RTYCID': 'ad399706d6e545c08a567306be5f2a8b', 'CT_TYCID': '3938c1972fe5473fa2a7b6690b1676a2', 'tyc-user-info': '%257B%2522myQuestionCount%2522%253A%25220%2522%252C%2522integrity%2522%253A%25220%2525%2522%252C%2522state%2522%253A%25220%2522%252C%2522vipManager%2522%253A%25220%2522%252C%2522onum%2522%253A%25220%2522%252C%2522monitorUnreadCount%2522%253A%25224%2522%252C%2522discussCommendCount%2522%253A%25220%2522%252C%2522token%2522%253A%2522eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNzE4MDQ3NTE2MyIsImlhdCI6MTU0MTk4NDQ4OSwiZXhwIjoxNTU3NTM2NDg5fQ.QloyEV9nPyAOuz2lcAlg9VHCX4r3xF-rlh76Sr9v0oHLFhQmRLYc3b24kr40CTubmyitrlTybSbRy23RSFcygA%2522%252C%2522redPoint%2522%253A%25220%2522%252C%2522pleaseAnswerCount%2522%253A%25220%2522%252C%2522vnum%2522%253A%25220%2522%252C%2522bizCardUnread%2522%253A%25220%2522%252C%2522mobile%2522%253A%252217180475163%2522%257D', 'auth_token': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNzE4MDQ3NTE2MyIsImlhdCI6MTU0MTk4NDQ4OSwiZXhwIjoxNTU3NTM2NDg5fQ.QloyEV9nPyAOuz2lcAlg9VHCX4r3xF-rlh76Sr9v0oHLFhQmRLYc3b24kr40CTubmyitrlTybSbRy23RSFcygA', 'cloud_token': '3b469e906aec44a5a81e451d70ebb90d', 'cloud_utm': '512d3ff8dc0c45aab61a5af04eb93c72', } driver.add_cookie({'name':'TYCID','value':cookies['TYCID']}) driver.add_cookie({'name':'undefined','value':cookies['undefined']}) driver.add_cookie({'name':'ssuid','value':cookies['ssuid']}) driver.add_cookie({'name':'Hm_lvt_e92c8d65d92d534b0fc290df538b4758','value':cookies['Hm_lvt_e92c8d65d92d534b0fc290df538b4758']}) driver.add_cookie({'name':'aliyungf_tc','value':cookies['aliyungf_tc']}) driver.add_cookie({'name':'csrfToken','value':cookies['csrfToken']}) driver.add_cookie({'name':'RTYCID','value':cookies['RTYCID']}) driver.add_cookie({'name':'CT_TYCID','value':cookies['CT_TYCID']}) driver.add_cookie({'name':'tyc-user-info','value':cookies['tyc-user-info']}) driver.add_cookie({'name':'auth_token','value':cookies['auth_token']}) driver.add_cookie({'name':'cloud_token','value':cookies['cloud_token']}) driver.add_cookie({'name':'cloud_utm','value':cookies['cloud_utm']}) driver.get('https://www.tianyancha.com/company/256283648')
有兩個需要注意的點:
一,需要先進入目標網站,然後在新增cookies,最後再次請求網站。否則會有以下報錯:
selenium.common.exceptions.WebDriverException: Message: unable to set cookie
(Session info: chrome=70.0.3538.77)
(Driver info: chromedriver=2.42.591088 (7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 10.0.17134 x86_64)
二:cookies中的值是通過 name,value來新增,所以過程比直接放到headers中要麻煩很多。