今天在mac環境下嘗試了一下用selenium連接現有的服務器,本來想繞過某寶的反爬蟲機制的,但是並沒有什麼用,但是這個技術不錯,我這裏分享一下實現過程。
- 添加環境變量
export PATH="/Applications/Google Chrome.app/Contents/MacOS:$PATH"
把上面的這一句添加到bashrc中,我的是zshrc,然後激活環境:
source ~/.zshrc
然後打開chrome:
Google\ Chrome --remote-debugging-port=9222 --user-data-dir="~/ChromeProfile"
運行這個後,就可以看見一個chrome打開了,接下來寫程序連接它:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
options = webdriver.ChromeOptions()
options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
options.add_experimental_option('excludeSwitches', ['enable-automation'])
browser = webdriver.Chrome(executable_path=chromedriver_path, options=options)
url='https://www.tmall.com/'
browser.get(url)
運行上面的代碼,會發現它連接到的是你剛纔打開的瀏覽器,是不是很簡單。
參考文獻
[1].How to connect Selenium to an existing browser that was opened manually?. https://cosmocode.io/how-to-connect-selenium-to-an-existing-browser-that-was-opened-manually/