1. 程式人生 > 其它 >使用selenium接管已開啟的瀏覽器

使用selenium接管已開啟的瀏覽器

第一步:新建一個對映,以儲存原來的chrome不被汙染

  • 新增環境變數

將chrome.exe放入系統環境變數中,找到驅動位置新增變數

  • 新建一個存放新環境的資料夾並對映

使用指令【chrome.exe --remote-debugging-port=9222 --user-data-dir="E:\data_info\selenium_data"】
其中--remote-debugging-port是建立新的移植位置,其中埠後面會使用(自定義), --user-data-dir是資料儲存的目錄(自定義)

此時會開啟一個網頁放著就行

第二步:selenium程式碼接管
通過下面的程式碼就可以登入知乎

import time
import json

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait


class ZhiHu:
    def __init__(self):
        self.url = 'https://www.zhihu.com/'
        self.chrome_options = Options()
        self.chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")  #  前面設定的埠號
        self.browser = webdriver.Chrome(executable_path=r'E:\Environment\python_global\Scripts\chromedriver.exe', options=self.chrome_options)  # executable執行webdriver驅動的檔案

    def get_start(self):
        self.browser.get(self.url)
        # time.sleep(20)  # 可以選擇手動登入或者是自動化,我這裡登入過就直接登陸了
        info = self.browser.get_cookies()  # 獲取cookies
        print(info)
        with open(r"..\download_txt\info.json", 'w', encoding='utf-8') as f:
            f.write(json.dumps(info))


if __name__ == '__main__':
    zhihu = ZhiHu()
    zhihu.get_start()


三、結果展示