有時須要在webDriver訪問網站時,附帶cookie實現免登錄訪問,如下是一個簡單的實現方式。python
''' 前面部分代碼用於填寫登陸信息並登陸 ''' # 獲取cookie並經過json模塊將dict轉化成str dictCookies = self.browser.get_cookies() jsonCookies = json.dumps(dictCookies) # 登陸完成後,將cookie保存到本地文件 with open('cookies.json', 'w') as f: f.write(jsonCookies)
# 初次創建鏈接,隨後方可修改cookie self.browser.get('http://xxxx.com') # 刪除第一次創建鏈接時的cookie self.browser.delete_all_cookies() # 讀取登陸時存儲到本地的cookie with open('cookies.json', 'r', encoding='utf-8') as f: listCookies = json.loads(f.read()) for cookie in listCookies: self.browser.add_cookie({ 'domain': '.xxxx.com', # 此處xxx.com前,須要帶點 'name': cookie['name'], 'value': cookie['value'], 'path': '/', 'expires': None }) # 再次訪問頁面,即可實現免登錄訪問 self.browser.get('http://xxx.com')