在X平台关注用户的Python代码报错求助:AttributeError问题
解决AttributeError: 'function' object has no attribute 'click'
你的问题出在对Selenium预期条件(EC)的使用方式上:EC.element_to_be_clickable本身是一个条件判断函数,不是直接返回元素的方法,单独赋值给变量后调用click()自然会报错——因为你操作的是函数对象,不是网页元素。
必须结合WebDriverWait来等待条件满足,才能获取到可交互的WebElement对象,修正后的代码如下:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By def follow_user(username): driver.get(f"https://x.com/{username}") # 初始化等待对象,最多等待10秒 wait = WebDriverWait(driver, 10) # 等待元素可点击并获取元素 follow = wait.until(EC.element_to_be_clickable((By.XPATH, '//span[text()="Follow"]'))) follow.click()
补充几点:
- 建议用
WebDriverWait替代time.sleep(2):固定等待时间容易受网络或页面加载速度影响,WebDriverWait会在元素满足条件时立即执行,稳定性更高。 - 更换
By.CSS_SELECTOR仍报错的原因相同——核心不是定位方式,而是没有通过WebDriverWait解析预期条件。如果用CSS选择器,同样需要配合等待,比如针对X的Follow按钮,可尝试更精准的选择器:follow = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div[data-testid="follow"] span')))
内容的提问来源于stack exchange,提问作者Piotr Misiuda
相关产品推荐
相关产品推荐

