0

I was writing test selectors for selenium in python for a website like Booking.com. For one example I had to automate selecting a button from a list of buttons. The format for the button is as under:

<button data-testid="selection-item" type="button" class="bf33709ee1 caf6d5613f cf9dc28f24 cce605d4d5 d7e4a4e122" fdprocessedid="0c0q3"><div class="da2b81213f f598d65660 ba88e720cd cfe5c03925 c6381d692a" style="--bui_stack_spaced_gap--s: 2;"><div class="e98ee79976 daa8593c50 be4746a572"><span class="bbbff1c622">Indian Rupee<div class=" f461050668">INR</div></span></div><div class=""></div></div></button>

How do I write a selector for a code that can help me select such currencies depending on its short code for ex: "INR" in this case. If I need to change to EUR, I only need to provide {currency} as a parameter.

I have tried Xpath, full XPath, CSS Selectors using class, data-testid among other visible things. The one that worked partially was to have selected_currency_element = self.find_elements(By.CSS_SELECTOR, "button[data-testid='selection-item']")[0] Here [0] was the first element, but I wanted to select using currency codes like "INR","USD","EUR"

2 Answers 2

0

You can try a xpath search like the following:

def select_currency(currency_code):
    # Create the XPath string
    xpath = f"//button[@data-testid='selection-item']//span[contains(text(), '{currency_code}')]"
    
    try:
        # Wait until the element is present
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, xpath))
        )
        # Click the button
        element.click()
        print(f"Selected currency: {currency_code}")
    except Exception as e:
        print(f"An error occurred: {e}")
2
  • I tried this but its only selecting the first item, even when I change currencies. Also there is a chance that some currencies may repeat (in a section where it says commonly used currencies) which are in the same pop-up.
    – Dark Geek
    Commented Jul 1 at 19:14
  • but the button have a unique xpath, you must find it and get it by xpath, if have multiple, element will return a list.
    – skulden
    Commented Jul 2 at 23:15
0

Going through what you need:

  • The button with @data-testid='selection-item'
    • Which contains a span, which contains a div, with text INR/USD/etc

//button[@data-testid='selection-item'] => gets the button //span/div[text()='INR'] => gets the second requirement

"//button[@data-testid='selection-item' and .//span/div[text()='INR']]" => combines both to what you need, get the button which contains the right div. The .// here says => look anywhere within this element

I use C# so I refer to the other answer for the code, but opening a browser, going to the dev tools and using: $x("//button[@data-testid='selection-item' and .//span/div[text()='INR']]") confirms that this works

Not the answer you're looking for? Browse other questions tagged or ask your own question.