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)
相关推荐
Yan-英杰7 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
小喵要摸鱼6 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn6 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML6 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
mengyoufengyu7 小时前
算法12-贪心算法
python·算法·贪心算法
T_Y99437 小时前
pythonrsa加密与sha256加密
python