Reputation: 11
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"
Upvotes: 0
Views: 57
Reputation: 232
Going through what you need:
//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
Upvotes: 0
Reputation: 423
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}")
Upvotes: 0