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

Python Selenium如何获取指定ol标签内的所有链接?

解决指定标签内链接获取问题

你的原代码会抓取页面上所有带href属性的<a>标签,要只获取<ol class="pagination__items">标签内的链接,只需修改XPath定位表达式,把查找范围限定在目标ol标签内部即可。

修改后的核心代码

直接调整XPath路径,定位到目标ol下的所有<a>标签:

chromedriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
chromedriver.get("https://www.ebay.co.uk/usr/username")
# 限定在class为pagination__items的ol标签内查找带href的a标签
links = chromedriver.find_elements("xpath", ".//ol[@class='pagination__items']//a[@href]")

for link in links:
    print(link.get_attribute("href"))

额外建议:添加显式等待

如果页面加载较慢,可能会出现找不到目标ol标签的情况,建议添加显式等待确保元素加载完成:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chromedriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
chromedriver.get("https://www.ebay.co.uk/usr/username")

# 等待目标ol标签加载完成,最多等10秒
wait = WebDriverWait(chromedriver, 10)
pagination_ol = wait.until(EC.presence_of_element_located(("xpath", ".//ol[@class='pagination__items']")))

# 从已加载的ol标签内查找链接
links = pagination_ol.find_elements("xpath", ".//a[@href]")

for link in links:
    print(link.get_attribute("href"))

内容的提问来源于stack exchange,提问作者Abdullah Ergun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:09:57