??前一篇文章主要介紹下載針對火狐瀏覽器的WebDriver,寫那篇文章時才找到能夠下最新版本Chrome的WebDriver地址(參考文獻6),本文繼續學習并驗證針對Chrome瀏覽器的WebDriver下載和使用方法。
Chrome的WebDriver版本與操作系統相關,也與Chrome的版本相關,通常與Chrome版本號的前三段相匹配,如下所示,如果是在64位Windows操作系統中使用版本為140.0.7312.0的Chrome瀏覽器,則應下載版本為140.0.7312.0的win64的chromedriver。注意!chromedriver的版本與Chrome的版本一定要對應,否則無法啟動Chrome瀏覽器。
??解壓chromedriver-win64.zip,并將chromedriver.exe文件放在Python安裝目錄的Scripts目錄下,然后調整之前的測試代碼進行驗證,示例代碼及運行效果如下所示:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import timedriver = webdriver.Chrome()
driver.get("https://www.baidu.com")time.sleep(2)search_box = driver.find_element(By.ID, "kw") # 百度搜索框的ID為"kw"
search_box.send_keys("DeepSeek官網")
search_box.send_keys(Keys.RETURN)time.sleep(3)first_result = driver.find_element(By.CSS_SELECTOR, "div.result:first-child h3 a")
first_result.click()
參考文獻:
[1]https://www.selenium.dev/zh-cn/
[2]https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/
[3]https://blog.csdn.net/kk_lzvvkpj/article/details/148610502
[4]https://registry.npmmirror.com/binary.html?path=chromedriver/
[5]https://chromedriver.chromium.org/
[6]https://googlechromelabs.github.io/chrome-for-testing/#stabl