You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium爬取lavoro.gov.it时元素无法点击的问题求助

解决Selenium翻页时'list' object has no attribute 'click'异常

错误原因

你代码里用了driver.find_elements(By.XPATH, ""),这个方法返回的是所有匹配元素的列表,而列表本身没有click()方法,直接调用自然会报错。另外注意你XPATH参数是空的,得填上你复制的分页箭头的真实路径。

解决方法

方法1:改用单数形式的find_element

这个方法返回单个匹配元素,找到后直接调用click()即可:

try:
    # 把引号里的内容替换成你复制的分页箭头的真实XPATH
    next_page_link = driver.find_element(By.XPATH, "//xpath/of/next/page/button")
    next_page_link.click()
except Exception as e:
    print('[DEBUG] Exception:', e)
    print('[DEBUG] break')
    break  # exit loop

方法2:从元素列表中取目标元素(多元素场景)

如果页面存在多个类似元素,确认要点击的是第一个,可从find_elements返回的列表中取索引0的元素:

try:
    next_page_links = driver.find_elements(By.XPATH, "//xpath/of/next/page/button")
    if next_page_links:  # 先判断列表不为空,避免索引越界
        next_page_links[0].click()
    else:
        print('[DEBUG] 未找到下一页按钮')
        break
except Exception as e:
    print('[DEBUG] Exception:', e)
    print('[DEBUG] break')
    break  # exit loop

额外优化建议

  • 用显式等待确保元素可点击:避免页面未加载完成就执行点击操作,减少报错概率:
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    try:
        # 等待10秒,直到元素可点击
        next_page_link = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//xpath/of/next/page/button"))
        )
        next_page_link.click()
    except Exception as e:
        print('[DEBUG] Exception:', e)
        print('[DEBUG] break')
        break  # exit loop
    
  • 验证XPATH有效性:在浏览器开发者工具控制台输入$x("你的XPATH"),看是否能准确定位到分页箭头,确保XPATH是正确的。

内容的提问来源于stack exchange,提问作者Roberto Artiaco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 03:19:56