Selenium4自动化测试2--元素定位By.ID,By.CLASS_NAME,By.TAG_NAME

三、元素定位方式

1-通过id定位,By.ID

id属性在HTML中是唯一的,因此使用id定位可以确保找到页面上唯一的元素。

由于id是唯一的,浏览器在查找元素时可以快速定位到目标元素,提高了定位的效率。

复制代码
import time

#pip install selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
# 指定浏览器的位置,解决浏览器驱动和浏览器版本不匹配的问题
chrome_location = r'D:\pythonProject2023\SeleniumFirst\chrome-win64\chrome.exe'
options = webdriver.ChromeOptions()
options.binary_location = chrome_location
driver = webdriver.Chrome(options=options)
# 使用get方法,访问网址
driver.get('https://www.baidu.com/')
#窗口最大化
driver.maximize_window()
#1 找到输入框的位置,输入万笑佛博客园
element = driver.find_element(By.ID,'kw')
element.send_keys("老虎资源分享")
#2 找到搜索框的位置,点击搜索
#单数查找
driver.find_element(By.CLASS_NAME,'s_btn').click()

time.sleep(3)
driver.quit()

2-通过类名定位,By.CLASS_NAME

复制代码
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
# 指定浏览器的位置,解决浏览器驱动和浏览器版本不匹配的问题
chrome_location = r'D:\pythonProject2023\SeleniumFirst\chrome-win64\chrome.exe'
options = webdriver.ChromeOptions()
options.binary_location = chrome_location
driver = webdriver.Chrome(options=options)
# 窗口最大化
driver.maximize_window()
driver.get("https://www.bilibili.com/")
# 只获取class属性的第一个元素
driver.find_element(By.CLASS_NAME,'nav-search-input').send_keys("老虎资源分享")
time.sleep(3)
driver.find_element(By.CLASS_NAME,'channel-link').click()
# 获取class属性的所有元素
# driver.find_elements(By.CLASS_NAME,'channel-link')[4].click()
# for ele in driver.find_elements(By.CLASS_NAME,'channel-link'):
#     print(ele.text)
# 错误用法
#driver.find_element(By.CLASS_NAME,'icon-bg icon-bg__channel').click()

time.sleep(3)

3-通过标签名定位,By.TAG_NAME

一个网页,相同的标签的元素的概率非常高,因为我们尽量少通过tag_name定位单个元素

复制代码
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
# 指定浏览器的位置,解决浏览器驱动和浏览器版本不匹配的问题
chrome_location = r'D:\pythonProject2023\SeleniumFirst\chrome-win64\chrome.exe'
options = webdriver.ChromeOptions()
options.binary_location = chrome_location
driver = webdriver.Chrome(options=options)


# 窗口最大化
driver.maximize_window()
driver.get("https://www.bilibili.com/")
driver.find_element(By.TAG_NAME, "input").send_keys("老虎资源分享")

time.sleep(3)
相关推荐
曲径海盗2 分钟前
【Python 学习第 32 天】字符串基础
python·学习笔记·编程入门
田里的水稻18 分钟前
PyTorch_torchvision---数据集下载\TensorBoard可视化
人工智能·pytorch·python·深度学习·机器学习
程序员正茂25 分钟前
Win11使用自定义训练集训练ncnn模型
python·yolo·图像识别·移动端·ncnn
zwd200531 分钟前
Manim 画布尺寸与像素换算详解:frame_width、frame_height、pixel_width 和画质参数(0.21.0 实测)
python·分辨率·manim·数学动画·frame_width·manim教程
最强小杰1 小时前
Claude Opus 4.8 调用报 529 怎么办?并发限制触发过载——退避策略与降级方案完整指南
运维·网络·python·ai
databook1 小时前
MinMax vs Standard vs Robust:三种特征缩放怎么选
python·机器学习·数据分析
在世修行1 小时前
智学文枢:实体模型层
python·orm·sqlalchemy
张张123y2 小时前
# 后端第七课:FastAPI 实战入门(用刚学的 Python 写第一个 API 接口)
开发语言·python·mysql·api·fastapi
CCblandy2 小时前
一致性哈希到底省了多少搬迁?本机实测 3 轮:取模 6→7 搬 85.8%,V=128 只搬 14.3%,虚拟节点太少会被倾斜骗
后端·python·云原生·性能优化·架构
Yan-英杰2 小时前
【论文精读】 基于 TensorFlow 对卷积神经网络的优化研究:异构式 CPU+GPU 协同计算 + ReLU-Swish 激活函数
python·卷积神经网络