0

Using Python 3.

Situation:

I select some elements with a certain xpath query.

There are many matches for that xpath query.

I want to grab the exact match corresponding with the element that is visible at the moment.

Notes:

There are always N matches (being N greater than 1.)

There is always only one match that is visible.

Actually, this is about pop-ups being displayed or not with javascript at certain moments.

Question:

How can iterate on all those results and know which one is visible by the user?

UPDATE:

The website is: go to website

If you wait a few seconds, there is a popup being displayed.

My xpath query is:

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

But there are 23 matches in this case.

How may I get the exact match that is being displayed?

I tried clicking it, which would give an exception when not visible.

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

2 Answers 2

1

Here a working example with Selenium. Instead of fiddling with finding the correct one by visibility, I get the offer ID from the URL and use that to find the correct element.

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Muchas gracias tito Paco. :) Wish you a great day.
0

My answer comes a little late but I think one of the ways to check if the element is visible is simply by checking its location on the screen. visible_elem = None

for elem in codigos_descuento:
    if elem.location["x"] > 0 and elem.location["y"] >0:
        visible_elem = elem
        print("Visible Element found!")
        break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.