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

Selenium如何编写XPath定位带rel=next属性的下一页按钮实现爬虫自动翻页

下一页按钮XPath定位解决方案

核心问题说明

你原有XPath失效的原因有两点:

  • 文本Kitas实际归属在<a>标签内部,而非<li>的直接文本,节点层级定位逻辑错误
  • 纯文本定位容易受页面空格、换行、本地化文本变动影响,稳定性远低于属性匹配

正确XPath写法

你明确要求匹配带rel="next"属性的按钮,优先使用属性匹配方案,稳定性最高:

//a[@rel="next"]

如果需要结合文本做双重校验,使用normalize-space清理文本前后空格后匹配:

//a[@rel="next" and normalize-space(text())="Kitas"]

修正后完整代码

建议增加显式等待逻辑,避免元素未加载完成就触发点击操作导致失效:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Safari()
driver.get('https://autoplius.lt/skelbimai/naudoti-automobiliai?make_id=43&model_id=186&make_date_from=1999&make_date_to=2005')

# 处理cookie弹窗
cookie = driver.find_element_by_xpath('//*[@id="onetrust-accept-btn-handler"]')
cookie.click()

# 等待下一页按钮可点击后触发点击
wait = WebDriverWait(driver, 10)
next_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//a[@rel="next"]')))
next_btn.click()

页面参考截图

页面截图

内容的提问来源于stack exchange,提问作者Perkūns

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:06:04