Python和Selenium-获取可见的元素

Python和Selenium-获取可见的元素,python,selenium,Python,Selenium,使用Python 3 情况: 我使用某个xpath查询选择一些元素 该xpath查询有许多匹配项 我想获取与当前可见元素对应的精确匹配 注释: 始终存在N个匹配项(N大于1。) 始终只有一个匹配项可见 实际上,这是关于在某些时刻是否使用javascript显示弹出窗口的问题 问题: 如何迭代所有这些结果并知道用户可以看到哪一个 更新: 网址为: 如果您等待几秒钟,将显示一个弹出窗口 我的xpath查询是: //div[@class='wrapper-code-reveal']//输入[@clas

使用Python 3

情况

我使用某个xpath查询选择一些元素

该xpath查询有许多匹配项

我想获取与当前可见元素对应的精确匹配

注释

始终存在N个匹配项(N大于1。)

始终只有一个匹配项可见

实际上,这是关于在某些时刻是否使用javascript显示弹出窗口的问题

问题

如何迭代所有这些结果并知道用户可以看到哪一个

更新

网址为:

如果您等待几秒钟,将显示一个弹出窗口

我的xpath查询是:

//div[@class='wrapper-code-reveal']//输入[@class='code']]

但在这种情况下有23个匹配项

如何获得显示的精确匹配

我试着点击它,当不可见时会出现异常

codigos_descuento = driver.find_elements_by_xpath("//div[@class='wrapper-code-reveal']//input[@class='code']")

for codigo in codigos_descuento:
    try:
        codigo.click()
        codigo_descuento_texto = codigo.get_attribute('value')
    except:
        print(traceback.format_exc())
        continue

这里是一个硒的工作示例。我从URL获取offer ID,并使用它来查找正确的元素,而不是通过可见性来找到正确的元素

from selenium import webdriver

driver = webdriver.Chrome()


def get_offer_id_from_url(url):
    offer_id = url.split('#')[1]
    offer_id = offer_id.split('-')[1]
    return offer_id


def get_discount_code(url, offer_id):
    offer_div_id = 'd-%s' % offer_id
    driver.get(url)
    discount_elem = driver.find_element_by_xpath(
        "//div[@id='%s']//input[@class='code']" % offer_div_id
    )
    discount_code = discount_elem.get_attribute('value')
    return discount_code


url = 'https://www.savoo.es/c-Alimentacion-codigo-promocional.html#p-5204957'
offer_id = get_offer_id_from_url(url)
discount_code = get_discount_code(url, offer_id)
print(discount_code)

我的答案来得有点晚,但我认为检查元素是否可见的方法之一就是检查它在屏幕上的位置。 可见元素=无

for elem in codigos_descuento:
    if elem.location["x"] > 0 and elem.location["y"] >0:
        visible_elem = elem
        print("Visible Element found!")
        break
穆查斯·格雷西亚斯·蒂托·帕科(Muchas gracias tito Paco.)祝你有美好的一天。