Skip to content

Selenium 使用规则

0、前置配置

python
import os.path
from selenium import webdriver  # 用于操作浏览器
from selenium.webdriver.chrome.options import Options  # 用于设置谷歌浏览器
from selenium.webdriver.chrome.service import Service  # 用于管理谷歌驱动


def setup():
    option = Options()
    option.add_argument('--no-sandbox')
    option.add_experimental_option('detach', True)
    chromedriver_path = os.path.join(os.path.dirname(__file__), 'chromedriver')
    service = Service(chromedriver_path)
    return webdriver.Chrome(options=option, service=service)

drive = setup()

1、打开指定网站

python
driver.get("https://www.baidu.com")

2、关闭浏览器

python
driver.quit()

3、关闭标签页

python
driver.close()

4、最大化 最小化窗口

python
driver.maximize_window()
driver.minimize_window()

5、浏览器打开位置

python
# 设置浏览器打开位置,x 为横坐标,y 为纵坐标, 单位为像素
driver.set_window_position(x, y)

6、浏览器打开大小

python
# 设置浏览器打开大小,width 为宽度,height 为高度, 单位为像素
driver.set_window_size(width, height)

7、浏览器截图

python
# 截图并保存为图片, 文件名可以自定义
driver.get_screenshot_as_file("screenshot.png")

8、刷新页面

python
# 刷新页面
driver.refresh()

9、隐性等待

python
# 元素定位隐形等待,指定多少秒内找到元素立刻执行,没有找到元素则报错
drive.implicitly_wait(30)

10、获取页面标题

python
# 获取页面标题
title = drive.title

11、获取页面源码

python
# 获取页面源码
source = drive.page_source

12、获取页面 URL

python
# 获取页面 URL
url = drive.current_url

13、新建标签页

python
# 新建标签页
drive.switch_to.new_window('tab')  # 打开新标签页
drive.switch_to.new_window('window')  # 打开新窗口

14、获取全部标签页句柄

python
handles =  drive.window_handles  # 获取所有标签页的句柄列表
handle = drive.current_window_handle  # 获取当前标签页的句柄

15、切换标签页

python
# 切换到指定的标签页
drive.switch_to.window(drive.window_handles[0])  # 切换到第一个标签页
drive.switch_to.window(drive.window_handles[-1])  # 切换到最后一个标签页

# 示例:遍历所有标签页
for handle in drive.window_handles:
    drive.switch_to.window(handle)
    print(drive.title)  # 打印每个标签页的标题

16、点击弹窗确认按钮

python
# 弹窗确认按钮
drive.switch_to.alert.accept()

17、点击弹窗取消按钮

python
# 弹窗取消按钮
drive.switch_to.alert.dismiss()

18、获取弹窗文本

python
# 获取弹窗文本,该语句必须在弹窗确认按钮和取消按钮之前
text = drive.switch_to.alert.text

19、输入弹窗文本

python
# 输入弹窗文本,该语句必须在弹窗确认按钮和取消按钮之前
drive.switch_to.alert.send_keys("test")

20、iframe 操作

python
# 切换到iframe
drive.switch_to.frame(drive.find_element(By.ID, "iframe_id"))
# 操作 iframe 中的元素
drive.find_element(By.ID, "element_id").click()
# 切换到主页面
drive.switch_to.default_content()

21、获取元素内容

python
# 获取元素内容
content = drive.find_element(By.ID, "element_id").text

22、获取元素属性

python
# 获取元素属性
attribute = drive.find_element(By.ID, "element_id").get_attribute("attribute_name")

23、判断元素是否可见

python
# 判断元素是否可见
visible = drive.find_element(By.ID, "element_id").is_displayed()

24、网页前进与后退

python
# 网页前进
drive.forward()
# 网页后退
drive.back()