Selenium Python报错:element_to_be_clickable()仅接受1个参数却传入2个
解决Selenium中element_to_be_clickable()的TypeError错误
错误原因
你遇到的TypeError: element_to_be_clickable() takes 1 positional argument but 2 were given错误,核心问题是调用EC.element_to_be_clickable()时参数格式错误:这个方法仅接受1个参数,即包含定位方式(如By.CSS_SELECTOR)和选择器字符串的元组,但你直接传入了两个独立参数。
另外,下载文件的XPath末尾多了/text(),会定位到文本节点而非可点击的<a>元素,这也会导致后续点击失败。
修正方案
- 所有
EC.element_to_be_clickable()调用,将定位参数用外层括号包裹,形成元组(比如(By.CSS_SELECTOR, "#searchButton")) - 修正下载链接的XPath,移除末尾的
/text()
修正后的完整代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import numpy as np import time options = Options() options.add_argument("--start-maximized") start = time.process_time() time.sleep(3) s = Service(path) # 注意这里的path需要你提前定义 driver = webdriver.Chrome(options=options, service=s) # 访问目标页面 page = 'https://www.idx.co.id/perusahaan-tercatat/laporan-keuangan-dan-tahunan/' driver.get(page) from selenium.webdriver.common.keys import Keys try: # 点击输入框并输入公司名称 wait = WebDriverWait(driver, 10) # 建议延长等待时间,避免页面加载不及时 inputElement = wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/main/div[1]/div[2]/div[3]/div/span/span[1]/span/ul/li/input"))) inputElement.send_keys(company, Keys.ENTER) # company需要提前定义 # 选择年份2022 inputElement2 = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="yearList"]/option[1]'))).click() # 选择报告期 inputElement3 = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#periodList > option:nth-child(3)"))).click() # 点击"Cari"按钮 - 修正参数为元组 wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#searchButton"))).click() except Exception as e: print(f"执行出错: {str(e)}") # 下载文件 - 修正XPath并调整参数格式 try: wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/main/div[2]/div/div/div[2]/div/dl/dd[5]/div[1]/a"))).click() except Exception as e: print(f"下载出错: {str(e)}") print('Execution Time: ', time.process_time() - start)
额外建议
- 把
WebDriverWait的超时时间从2秒延长到10秒左右,避免因页面加载缓慢导致元素未找到 - 避免使用绝对XPath(比如
/html/body/...),尽量使用相对定位或更稳定的属性定位,防止页面结构变动后脚本失效 - 不要用空的
except: pass,至少打印错误信息方便排查问题
内容的提问来源于stack exchange,提问作者Luc
相关产品推荐
相关产品推荐

