python 如何在Selenium中将参数传递给find_element?

von4xj4u  于 2023-05-16  发布在  Python
关注(0)|答案(1)|浏览(246)

目前,我正在练习使用Selenium进行网站测试。然而,我遇到了一个问题,我无法将参数传递给def函数。

from booking.booking import Booking
    with Booking() as test:

    test.change_currency(currency='USD')`
def change_currency(self, currency=None):

    currency_element = self.find_element(By.XPATH, '//*[@id="b2indexPage"]/div[1]/div/header/nav[1]/div[2]/span[1]/button')
    currency_element.click()

    selected_currency_element = self.find_element(By.?, '?')
    selected_currency_element.click()

以下是我尝试测试的网站:https://www.booking.com/
Image of inspect
我尝试了各种方法,使用By.CSS和By.XPATH方法。

wgmfuz8q

wgmfuz8q1#

您可以尝试在booking.com上使用不同的货币进行更改和测试,下面是我的实现:

import time
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC

def change_currency(currency):
    currency_list = driver.find_element(By.CSS_SELECTOR, 'div[data-testid="All currencies"]').find_elements(By.TAG_NAME, 'button')

    for curr in currency_list:
        code = curr.text.split('\n')[1]
        if code == currency:
            curr.click()
            return True

driver = Chrome()
driver.get("https://www.booking.com/")
wait = WebDriverWait(driver, 10)

# wait and click to open the "Select your currency" pop-up
currency_button = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'button[data-testid="header-currency-picker-trigger"]')))
currency_button.click()

# wait and click to close the sign-in pop-up
sign_in = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'button[aria-label="Dismiss sign-in info."]')))
sign_in.click()

# change the currency to Thai Baht
change_currency('THB')
time.sleep(5)

正如你所看到的,函数change_currency('THB')将货币更改为Thai Baht。类似地,您可以通过从货币循环中调用此函数来为多个货币执行此操作。

相关问题