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)
相关推荐
满怀冰雪15 分钟前
25-迁移学习入门:加载预训练模型并微调
人工智能·python·机器学习·迁移学习·paddle
2601_9622845016 分钟前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_9620780328 分钟前
构建RESTful APIs:使用Python和Flask
python·flask·web开发·api设计·构建restfulapis
半亩码田29 分钟前
C#转Python第4.5篇:单元测试:pytest vs xUnit/NUnit
python·单元测试·c#
2601_9623008134 分钟前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
Zane199437 分钟前
两个线程算两遍循环,为什么只快了一点点不是两倍?GIL连环追问
后端·python
重生之小比特37 分钟前
【Java SE】程序逻辑控制
java·开发语言·python
小灰灰搞电子41 分钟前
Python 函数参数分隔符 *:Keyword-Only Arguments 原理与实践
开发语言·python
2601_9622972544 分钟前
Authlib 0.13通用Python认证授权库wheel安装包(支持Python 2/3)
python·jwt·oauth2.0·authlib·openidconnect
SamChan901 小时前
大文件多语言PDF翻译性能实测:300页文档的耗时、内存占用与失败率分析
python·ai·pdf·机器翻译