selenium学习1_使用selenium,chromedriver打开百度并进行搜索

一、需要安装Python,selenium,chrome浏览器,以及与之版本对应的chromedriver。

具体安装包以及安装步骤自己去百度,这里只讲这些软件安装使用之间的关联。

  1. selenium下载安装之后将其放在Python路径下就不需要再配置环境了,当你打开pycharm时会在External libraries路径下找到,创建.py文件也可以直接"from selenium import xxxxx"了。
    selenium学习1_使用selenium,chromedriver打开百度并进行搜索_第1张图片
    selenium学习1_使用selenium,chromedriver打开百度并进行搜索_第2张图片

  2. chromedriver.exe版本要和chrome浏览器版本对应,
    selenium学习1_使用selenium,chromedriver打开百度并进行搜索_第3张图片
    chromedriver版本url为:
    https://chromedriver.storage.googleapis.com/index.html
    去里面寻找对应版本的

  3. WebDriver下载好之后,解压缩获得chromedriver.exe,需要在chrome浏览器和Python路径下都放置一份。
    chrome浏览器路径如下:
    selenium学习1_使用selenium,chromedriver打开百度并进行搜索_第4张图片
    selenium学习1_使用selenium,chromedriver打开百度并进行搜索_第5张图片
    Python浏览器路径如下:
    selenium学习1_使用selenium,chromedriver打开百度并进行搜索_第6张图片

2、代码块如下

from selenium import webdriver
from selenium.webdriver.common.by import By


# 使用chromedriver.exe打开谷歌浏览器
browser = webdriver.Chrome()

# 通过网址打开百度网页
browser.get('https://www.baidu.com')

#在百度搜索框中输入关键字"python"

# browser.find_element_by_id("kw").send_keys("python")
browser.find_element(By.ID, "kw").send_keys("python")


#单击搜索按钮
# browser.find_element_by_id("su").click()
browser.find_element(By.ID, "su").click()

其中注释掉的代码部分,其语法格式是selenium4.x之前版本适用的,4.x之后find_element元素定位部分代码语法有所改变,需要用未注释部分的代码格式

具体我参考了一篇博文:https://blog.csdn.net/m0_49076971/article/details/126233151

你可能感兴趣的:(selenium,学习,python)