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)
相关推荐
Freak嵌入式15 分钟前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
java·开发语言·数据结构·python·接口·抽象基类
crownyouyou26 分钟前
最简单的一文安装Pytorch+CUDA
人工智能·pytorch·python
鸽芷咕29 分钟前
【Python报错已解决】libpng warning: iccp: known incorrect sRGB profile
开发语言·python·机器学习·bug
WenGyyyL30 分钟前
变脸大师:基于OpenCV与Dlib的人脸换脸技术实现
人工智能·python·opencv
laofashi201536 分钟前
AirTest 基本操作范例和参数解释(一)
python·自动化·automation
XyLin.38 分钟前
Msf之Python分离免杀
开发语言·python·网络安全·系统安全
Snowbowღ1 小时前
OpenAI / GPT-4o:Python 返回结构化 / JSON 输出
python·json·openai·api·gpt-4o·pydantic·结构化输出
计算机学姐1 小时前
基于python+django+vue的家居全屋定制系统
开发语言·vue.js·后端·python·django·numpy·web3.py
ac-er88881 小时前
常见的反爬虫和应对方法
开发语言·python
FL16238631291 小时前
基于yolov5的混凝土缺陷检测系统python源码+onnx模型+评估指标曲线+精美GUI界面
人工智能·python·yolo