selenium 使用已經(jīng)打開的chrome瀏覽器

一、背景

使用已經(jīng)打開的chrome瀏覽器主要是一下幾點原因:

? ? ? 1.? 使用已經(jīng)打開的chrome瀏覽器保存的登錄狀態(tài); 這樣避免需要輸入賬號密碼,可以直接進行相關(guān)操作,如爬蟲等;

? ? ? 2.? 有些網(wǎng)站間隔多久未使用后,需要重新使用驗證碼等方式進行驗證登錄,這樣很不利于自動化。如果我們可以用本機日常已經(jīng)打開的chrome瀏覽器,就可以有效解決此問題;


二、 操作步驟

以下主要在Ubuntu下的操作,不涉及window與mac

2.1? 起一個debug的chrome瀏覽器窗口

可以在命令行里這樣啟動:?/opt/google/chrome/chrome --remote-debugging-port=9222??--user-data-dir= “設(shè)置為user-data的路徑”這樣就會啟動一個瀏覽器。但是關(guān)閉終端,瀏覽器就關(guān)掉了??梢栽趗buntu中右鍵鎖定鎖定到啟動器,下次直接點這個快捷圖標就可以了。執(zhí)行上面操作后,其實會在~/.local/share/applications下生成一個chrome.desktop文件,vim看一下內(nèi)容:

[Desktop Entry]

Encoding=UTF-8

Version=1.0

Type=Application

Name=這里表示默認的標題

Icon=google-chrome

Path=/home/google/driver? # 這里是配置chrome對應chromedriver的目錄,比如chromedriver在/home/google/driver下,這里應該也可以不要的

Exec=/opt/google/chrome/chrome -remote-debugging-port=9222 --user-data-dir=設(shè)置為user-data的路徑

StartupNotify=false

StartupWMClass=Google-chrome

OnlyShowIn=Unity;

X-UnityGenerated=true

MimeType=x-scheme-handler/unknown;x-scheme-handler/about;x-scheme-handler/https;x-scheme-handler/http;text/html;

后面這邊默認就行


2.2 配置一個本機主用的chrome瀏覽器

這里一個debug的chrome瀏覽器,用來跑selenium的。另外一個正常工作使用的。配置正常工作使用的跟上面方法一樣:

在~/.local/share/applications生成一個google-chrome.desktop

[Desktop Entry]

Encoding=UTF-8

Version=1.0

Type=Application

Name=Google Chrome

Icon=google-chrome

Exec=/opt/google/chrome/chrome --profile-directory=Default

StartupNotify=false

StartupWMClass=Google-chrome

OnlyShowIn=Unity;

X-UnityGenerated=true

注意這里的Exec=/opt/google/chrome/chrome --profile-directory=Default設(shè)置為默認的。

2.3 代碼實現(xiàn)

# -*- coding: utf-8 -*-

fromseleniumimportwebdriver

fromselenium.webdriver.chrome.optionsimportOptions

chrome_options = Options()

chrome_options.add_experimental_option("debuggerAddress","127.0.0.1:9222")

chrome_driver ="XXXX/chromedriver"

driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)

driver.get('www.baidu.com')

這里的chrome_driver通過https://sites.google.com/a/chromium.org/chromedriver/downloads獲取與本機相同版本的driver文件。查看本機chrome版本號可以在chrome瀏覽器中輸入:chrome://verison即可。

注意這里的chromedriver需要加入到環(huán)境變量中,否則會出現(xiàn)以下異常:

create chrome driver error, Message: 'chromedriver' executable needs to be in PATH。Please see https://sites.google.com/a/chromium.org/chromedriver/home

如下方式添加到環(huán)境變量中:

1. sudo vim? /etc/profile

2. 末尾加上: export PATH=$PATH:chromedriver存放的絕對路徑

3.??source etc/profile

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容