我正在用 python 为 Booking.com 这样的网站编写 selenium 测试选择器。例如,我必须自动从按钮列表中选择一个按钮。按钮的格式如下:
<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>
如何编写一个代码选择器,可以帮助我根据其短代码选择此类货币,例如:在本例中为“INR”。如果我需要更改为欧元,我只需要提供 {currency} 作为参数即可。
我尝试过 Xpath、完整的 XPath、使用类、data-testid 等可见事物的 CSS 选择器。部分起作用的是
selected_currency_element = self.find_elements(By.CSS_SELECTOR, "button[data-testid='selection-item']")[0]
这里 [0] 是第一个元素,但我想选择使用“INR”、“USD”、“EUR”等货币代码
您可以尝试如下 xpath 搜索:
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}")