python selenium chrome 載入本地用戶配置

  • 2020 年 3 月 17 日
  • 筆記

google瀏覽器版本

Google Chrome : 79.0.3945.88 (正式版本) (64 位) (cohort: Stable)

查看chrome資訊:

chrome://version/

python selenium chrome 載入本地用戶配置,並cookie保存到本地文件

#!/usr/bin/env python  # encoding: utf-8  from selenium import webdriver  import time  import json      class Spider:      def main(self, url):          option = webdriver.ChromeOptions()          option.add_argument(r'--user-data-dir=C:UsersUserAppDataLocalGoogleChromeUser Data')          option.add_argument('--profile-directory=Default')          browser = webdriver.Chrome(options=option)          browser.get(url)          browser.implicitly_wait(60)          time.sleep(20)          try:              # 獲取登陸成功後的cookie資訊              login_rear_cookie = browser.get_cookies()              if login_rear_cookie:                  # 把cookie資訊用json序列化後寫入cookie.txt文件                  with open('cookie.txt', 'w') as f:                      f.write(json.dumps(login_rear_cookie))                  print('獲取cookie資訊成功')          except Exception as e:              print('獲取cookie失敗:{}'.format(e))          finally:              browser.quit()      if __name__ == '__main__':      url = "https://www.jd.com/"      st = Spider()      st.main(url)