【03】Selenium+Python 八种定位元素方法

操作元素,需要先查找定位到对应的元素。

查找单个元素:driver.find_element() 返回是一个web element 对象

查找多个元素:driver.find_elements() 返回是一个list对象

By 是 Selenium 中一个非常重要的类,用于定位网页元素。

使用需要导入By模块

python 复制代码
from selenium.webdriver.common.by import By  # 导入 By 模块

常用方法及示例

1. By.ID

根据元素的 ID 定位。

ID一般不会重复。

python 复制代码
element = driver.find_element(By.ID, "kw")

2.By.NAME

根据元素的 名称 定位。

python 复制代码
element = driver.find_element(By.NAME, "wd")

3.By.CLASS_NAME

根据元素的 类名 定位。

python 复制代码
element = driver.find_element(By.CLASS_NAME, "s_ipt")

4.By.TAG_NAME

根据元素的 标签名 定位。

一般与driver.find_elements()方法一起使用,因为一个页面中tag name非常容易重复。

python 复制代码
element = driver.find_elements(By.TAG_NAME,'input')
print(type(element))

find_elements 返回的是list 可以通过遍历list的方法获取每个元素

5.By.LINK_TEXT

根据元素的 链接文本 定位。

python 复制代码
element = driver.find_element(By.LINK_TEXT, "新闻")

6.By.PARTIAL_LINK_TEXT

根据元素的 部分链接文本 定位。

同样还是上面那个新闻链接。这样也能找到。

python 复制代码
element = driver.find_element(By.PARTIAL_LINK_TEXT, "新")

7.By.XPATH

根据元素的 XPath 定位。

在对应元素上,右键,copy,可复制xpath路径。

python 复制代码
    #复制的相对路径
    element = driver.find_element(By.XPATH, "//*[@id='kw']")
    #复制的绝对路径 很长不推荐使用
    element = driver.find_element(By.XPATH, "/html/body/div/div[2]/div[5]/div[1]/div/form/span[1]/input")
    #自己手写路径匹配规则
    element = driver.find_element(By.XPATH, "//input[@id='kw' and @name='wd' ]")

8.By.CSS_SELECTOR

根据元素的 CSS选择器 定位。

这个同样也可以在对应元素上,右键,copy,复制CSS选择器。

python 复制代码
# 复制的selector
driver.find_element(By.CSS_SELECTOR,"#kw")
#自己手写
element = driver.find_element(By.CSS_SELECTOR, "input[name='wd']")
相关推荐
寻星探路13 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
ValhallaCoder16 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
猫头虎16 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
八零后琐话17 小时前
干货:程序员必备性能分析工具——Arthas火焰图
开发语言·python
青春不朽51218 小时前
Scrapy框架入门指南
python·scrapy
AI袋鼠帝18 小时前
Claude4.5+Gemini3 接管电脑桌面,这回是真无敌了..
人工智能·windows·aigc
MZ_ZXD00119 小时前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·vue.js·spring boot·python·django·php
獨枭19 小时前
Windows 下安装与使用 Miniconda 完整指南
windows
全栈老石19 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python