selenium

selenium

Jiu_Ying Lv3

一、环境搭建

1. 安装三方库

1
2
3
pip install selenium
pip install password
pip install time

2. 安装浏览器驱动

微软Edge浏览器的Driber
Edge Driver

谷歌Chrome浏览器的Driber
Chrome Driver

简单起见将下载的driver.exepy文件放在同一目录下,可以不用配置环境变量。

二、初始化

1. 导入模块

1
2
3
4
5
6
7
# >>> -------- 导入模块 -------- <<<
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import password

2. 设置浏览器配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# >>> -------- 设置浏览器配置 -------- <<<
def Auto():

    # 设置浏览器选项
   
    rio = Options()

    # 禁用浏览器沙盒模式

    rio.add_argument('--no-sandbox')

    # 最大化浏览器窗口

    rio.add_argument('--start-maximized')

    # 保持浏览器打开状态

    rio.add_experimental_option('detach', True)

    # 设置浏览器路径

    RIO = webdriver.Chrome(service=Service(r'.\chromedriver.exe'), options=rio)

    return RIO
   
RIO=Auto()

3. 打开网站

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# >>> -------- 运行逻辑 -------- <<<
# 打开网页
RIO.get('URL')

# 等待网页加载完成
time.sleep(1)

# 点击登录按钮
RIO.find_element(By.CSS_SELECTOR, '').click()

# 输入用户名密码
RIO.find_element(By.ID, '').send_keys(password.username)
RIO.find_element(By.ID, '').send_keys(password.password)

# 点击登录按钮
RIO.find_element(By.CSS_SELECTOR, '').click()

# 获取当前时间并格式化
current_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')

# 截图(当前时间)
RIO.save_screenshot(f'screenshot_{current_time}.png')

# 等待条码打印完成
time.sleep(8)

4. 程序的最后关闭浏览器驱动

1
2
# 退出浏览器并释放驱动
RIO.quit()

三、选择元素

1. 根据ID查找

1
element = wd.find_element(By.ID, 'ID值')

2. 根据CSS选择器查找

1
element = wd.find_element(By.CSS_SELECTOR, 'css选择器')

3. 其他查找方法

1
2
element = wd.find_element(By.CLASS_NAME, 'class属性')
element = wd.find_element(By.TAG_NAME, '标签名')

4. FIND_ELEMENT与FIND_ELEMENTS

1
2
find_element返回一个元素(第一个)
find_elements返回元素列表

四、操作元素

1. 输入文字:SEND_KEYS()

1
element.send_keys('文本')			# 用于文本框

2. 点击:CLICK()

1
element.click()			# 用于按钮、超链接、单选框、多选框、

3. 下拉框选择

1
2
3
s = Select(element)
s.select_by_value('value值')
# s.select_by_visible_text('文本信息')

五、切换窗口

1. IFRAME

1
2
3
4
5
6
# 进入到iframe
wd.switch_to.frame('iframe名')
# wd.switch_to.frame(element)

# 回到原页面
wd.switch_to.default_content()

2. 切换页面

1
2
3
4
for window_handle in wd.window_handles:
wd.switch_to.window(window_handle)
if '内容' in wd.title:
break

六、打包程序

安装打包程序库

1
pip install pyinstaller

待打包程序图标放在同一级目录中,然后执行命令

1
Pyinstaller -F -w -i *.ico *.py
  • 标题: selenium
  • 作者: Jiu_Ying
  • 创建于 : 2025-08-27 03:15:38
  • 更新于 : 2025-08-27 03:15:38
  • 链接: http://rio.jiu-ying.top/2025/08/27/selenium/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论