python - Python selenium 不能在 2 个 Web 元素的同一位置执行 if 语句,但 id 不同
问题描述
有 2 个 div idphone_number_1-42
并contact_seller_1-42
以随机顺序排列。
我正在尝试做简单的事情,但找不到任何可行的方法。
phone_reveal_1 = driver.find_element_by_id('phone_number_0')
contact_seller_1= driver.find_element_by_id('contact_seller_0')
if phone_reveal_1:
else:
contact_seller_1.click()
我尝试使用isEnabled
, .size() != 0
, >0
,None
但它不会点击。任何想法?
解决方案
有两种方法可以检查元素是否存在。您应该使用find_elements
而不是find_element
.
findElement
方法用于访问页面上的单个 Web 元素。它返回第一个匹配元素。当找不到 If 元素时,它会抛出NoSuchElementException
异常。
findElements
方法返回所有匹配元素的列表。当元素不可用或页面上不存在时,findElements 方法返回一个空列表。它不抛出NoSuchElementException
。
使用if
else
:
phone_reveal_1 = driver.find_elements_by_id('phone_number_0')
contact_seller_1 = driver.find_elements_by_id('contact_seller_0')
if len(phone_reveal_1) > 0:
phone_reveal_1[0].click()
elif len(contact_seller_1) > 0:
contact_seller_1[0].click()
else:
print("both element are not there")
使用try
except
:
try:
driver.find_element_by_id('phone_number_0').click()
except NoSuchElementException:
try:
driver.find_element_by_id('contact_seller_0').click()
except NoSuchElementException:
print("both element are not there")
推荐阅读
- python - 从给定的整数列表中返回差为 2 的所有整数对
- python - 在 sphinx-autodoc 中对成员进行不区分大小写的排序
- r - 关于 R 中优化的问题
- java - 在 Spring Boot 项目中声明同一类/DAO 的多个实例是否有害?
- angular - 如何从Angular http post返回OKObjectResult作为字符串
- reactjs - 使用 Apollo react 用于 S3 图像上传的 useMutation 加载器
- machine-learning - 非凸优化
- css - 如何从左到右逐渐改变元素的背景颜色
- java - 有没有办法验证正则表达式在 Java 中完全匹配?
- python - Keras:keras 模型的二阶导数始终为 0