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

如何用XPath选取不含URL的元素?Selenium代码修正求助

解决Selenium中获取无URL的当前页码元素问题

原代码问题分析

你写的XPATH //*[@id="pagination"]/ul/li[2][not(/a[@href])] 出错的核心原因是:/a 是从根节点开始查找a标签,而非当前li元素的子节点,导致这个过滤条件完全失效,自然会选中所有符合位置的li元素。

正确XPATH写法

结合你的场景(当前页码元素无a标签或a标签不含href属性),给出两种精准写法:

  1. 匹配无嵌套a标签的当前页码li
    当前页码通常会被标记为active类,结合这个特征可以避免误选:
driver.find_element(By.XPATH, '//*[@id="pagination"]/ul/li[@class="active" and not(.//a)]')
  1. 匹配有a标签但无href属性的当前页码li
    如果页面里当前页码的li嵌套了a标签但没有href,用这个:
driver.find_element(By.XPATH, '//*[@id="pagination"]/ul/li[@class="active" and not(.//a/@href)]')

关键说明

  • .//a:用相对路径表示当前li元素下的所有后代a标签,这是和原代码/a的核心区别
  • @class="active":利用页面的激活状态标记,精准定位当前页码,避免选中其他li元素
  • not(...):过滤掉包含有效href的a标签元素

完整操作代码示例

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
driver.get("https://smartjobs.qld.gov.au")

# 滚动到底部
ActionChains(driver).scroll_to_element(driver.find_element(By.TAG_NAME, "footer")).perform()
# 点击Search按钮
driver.find_element(By.XPATH, "//button[text()='Search']").click()

# 新页面滚动到底部
ActionChains(driver).scroll_to_element(driver.find_element(By.TAG_NAME, "footer")).perform()

# 获取当前页码元素
current_page = driver.find_element(By.XPATH, '//*[@id="pagination"]/ul/li[@class="active" and not(.//a/@href)]')
print("当前页码:", current_page.text)

driver.quit()

内容的提问来源于stack exchange,提问作者Frankie Chan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:07:42