一、新建项目

二、安装 selenium

selenium 是浏览器自动化测试工具。

控制台输入

1
pip install selenium

三、下载 Microsoft Edge WebDriver

浏览器驱动,代码打开浏览器必须要有浏览器的驱动,不同版本的浏览器驱动也是不一样的

下载地址https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/?form=MA13LH

Microsoft Edge 浏览器 查看版本

打开 https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/?form=MA13LH

随意解压至一个目录

四、代码打开浏览器

1.新建 openEdgedriver.py 文件

2.写入代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from selenium import webdriver
from selenium.webdriver.edge.service import Service

# 指定 WebDriver 路径
path = "D:/temp/msedgedriver.exe" # 替换为你的 msedgedriver.exe 路径

# 使用 Service 类
service = Service(path)
browser = webdriver.Edge(service=service)

# 打开 百度网页
browser.get('[edge://newtab/](https://www.baidu.com)')

# 防止浏览器退出
input("按回车键退出...")
browser.quit()

3.运行 openEdgedriver.py 文件

将自动打开浏览器并且访问目标页面 edge://newtab/

五、实现页面里搜索框输入内容,并点击查询

既然是脚本,我们不能只是访问页面,肯定还要有点击事件

进入页面 https://www.baidu.com 查看页面源代码,我们发现,输入框<input>标签的 id 为 search-blog-words ;查询按钮<a> 标签有个属性 class ,为 btn-search-blog

查询 id 为 search-blog-words的属性,向其输入“京东准点秒杀脚本”

browser.find_element_by_id(“search-blog-words”).send_keys(“京东准点秒杀脚本”)

查询按钮 clsss 名称为 btn-search-blog 的标签,点击按钮

browser.find_element_by_class_name(‘btn-search-blog’).click()

分别是输入内容,点击查询。新修改后的代码为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By # 导入 By 类

# 指定 WebDriver 路径
path = "D:/temp/msedgedriver.exe" # 替换为你的 msedgedriver.exe 路径

# 使用 Service 类
service = Service(path)
browser = webdriver.Edge(service=service)

# 打开百度首页
browser.get('https://www.baidu.com')

# 定位搜索框并输入内容
browser.find_element(By.ID, "kw").send_keys("人间词话") # 输入内容

# 定位搜索按钮并点击
browser.find_element(By.ID, "su").click() # 点击搜索按钮

# 防止浏览器退出
input("按回车键退出...")
browser.quit()

再次运行代码