当我运行以下代码时,出现错误
TypeError: element_to_be_clickable() takes 1 positional argument but 2 were given
:
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
url = 'https://www.expedia.co.uk/'
s = Service(ChromeDriverManager().install())
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
driver = webdriver.Chrome(service=s, options=chrome_options)
driver.get(url)
elem = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.CSS_SELECTOR, "#add-flight-switch"))
elem.click()
elem1 = driver.find_element(By.XPATH, "button[aria-label='Leaving from']").text
driver.quit()
我可以看到
elements_to_be_clickable()
函数中确实有两个参数,但是 By.CSS_SELECTOR
部分不需要通过特定的选择器类型(在本例中为 CSS)来查找吗??
我正在使用选择器中心来获取 CSS_SELECTOR 信息。
非常感谢任何有关如何解决的支持。
您确实需要
By
和值,但该函数希望将两个值打包为 1,在 tuple
中
EC.element_to_be_clickable((By.CSS_SELECTOR, "#add-flight-switch"))
如果深入查看源代码,您将看到
element_to_be_clickable
在内部使用 _find_element
,此函数将 tuple
解压以在 driver.find_element()
中使用
class element_to_be_clickable(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
element = visibility_of_element_located(self.locator)(driver)
...
class visibility_of_element_located(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
return _element_if_visible(_find_element(driver, self.locator))
...
def _find_element(driver, by):
...
return driver.find_element(*by)
...
之前的答案很棒,我想贡献一下,您只需要按照函数的预期添加一些括号即可。这对我有用。
elem = WebDriverWait(driver,10).until((EC.element_to_be_clickable(By.CSS_SELECTOR, "#add-flight-switch")))
所有答案都非常出色。但我认为支架应该覆盖可点击的部分。像这样
elem = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#add-flight-switch")))