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)
相关推荐
郝学胜-神的一滴40 分钟前
Effective Python 第44条:用纯属性与修饰器取代旧式的 setter 与 getter 方法
开发语言·python·程序人生·软件工程
嫂子的姐夫2 小时前
11-py调用js
javascript·爬虫·python·网络爬虫·爬山算法
图亚Vanta3 小时前
Python入门第一课:Python安装、VSCode/Pycharm配置
vscode·python·pycharm
睿思达DBA_WGX3 小时前
使用 python-docx 库操作 word 文档(2):在word文档中插入各种内容
python·word
kunge1v54 小时前
学习爬虫第五天:自动化爬虫
爬虫·python·自动化
m***记4 小时前
Python 自动化办公的 10 大脚本
windows·python·自动化
人间乄惊鸿客4 小时前
python - 第二天
python
江上月5134 小时前
django与vue3的对接流程详解(上)
后端·python·django
老歌老听老掉牙4 小时前
基于 PyQt5 实现刀具类型选择界面的设计与交互逻辑
python·qt·交互
可触的未来,发芽的智生4 小时前
触摸未来2025.10.09:记忆的突围,从64个神经元到人工海马体神经网络
人工智能·python·神经网络·机器学习·架构