如何在Selenium的find_element中传递参数?函数传参问题求助
解决Selenium自定义函数传参及Booking.com货币元素定位问题
问题核心
你调用change_currency(currency='USD')时已传递参数,但函数内部未使用该参数做元素定位,再加上原定位逻辑为空,导致无法找到目标货币元素。
修复后的完整函数代码
结合Booking.com的实际DOM结构,以下是可运行的实现:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def change_currency(self, currency=None): # 显式等待货币切换按钮加载并可点击 currency_element = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.XPATH, '//*[@id="b2indexPage"]/div[1]/div/header/nav[1]/div[2]/span[1]/button')) ) currency_element.click() if not currency: return # 通过data属性定位目标货币(稳定性更高) selected_currency_element = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, f'a[data-modal-header-async-url-param*="selected_currency={currency}"]')) ) selected_currency_element.click()
关键细节说明
- 参数利用:函数通过
currency参数动态拼接定位表达式,直接关联你传入的'USD'参数,解决传参无效的问题。 - 稳定定位:使用
data-modal-header-async-url-param属性定位,避免页面语言切换、文本格式变化导致的定位失效。 - 显式等待:替换原直接
find_element的方式,确保元素加载完成后再操作,解决页面加载延迟导致的定位失败。
备选定位方式(文本匹配)
如果需要通过货币文本定位,可替换上述定位逻辑为:
selected_currency_element = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.XPATH, f'//span[contains(text(), "{currency}")]/parent::a')) )
内容的提问来源于stack exchange,提问作者Yuki
相关产品推荐
相关产品推荐

