首页 > 解决方案 > Python selenium 不能在 2 个 Web 元素的同一位置执行 if 语句,但 id 不同

问题描述

有 2 个 div idphone_number_1-42contact_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, >0None但它不会点击。任何想法?

标签: pythonseleniumselenium-webdriverautomated-tests

解决方案


有两种方法可以检查元素是否存在。您应该使用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")

推荐阅读