学习Python中Selenium模块的基本用法(3:下载浏览器驱动续)
前一篇文章主要介绍下载针对火狐浏览器的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