
本文介绍如何利用 selenium 4.8 在动态网页中定位并批量提取符合结构特征的 `` 标签 `href` 属性,生成可迭代的 url 列表,适用于多级嵌套、类名含空格或动态加载的场景。
在使用 Selenium 进行网页链接提取时,关键在于精准定位元素与可靠等待机制。针对您提供的 HTML 结构(
,其内嵌 ),直接使用 find_elements 配合 XPath 是高效方案。但需注意:类名中含空格(如 "programme titles")不能用 . 连接 CSS 选择器,必须改用 XPath 的 @class 属性匹配或 contains() 函数。
以下为完整、健壮的实现代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
# 可选:无头模式(适合服务器环境)
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
wait = WebDriverWait(driver, 25) # 最长等待25秒
try:
driver.get("https://your-target-website.com") # 替换为目标URL
# ✅ 推荐XPath:精确匹配多级结构 + 处理含空格的class
links = wait.until(
EC.presence_of_all_elements_located(
(By.XPATH, '//li//h4[@class="programme titles"]/a[@class="br-blocklink__link"]')
)
)
# 提取所有 href 属性,自动过滤 None 值
href_list = [elem.get_attribute("href") for elem in links if elem.get_attribute("href")]
print(f"成功提取 {len(href_list)} 个链接:")
for i, url in enumerate(href_list, 1):
print(f"{i}. {url}")
# 后续可遍历处理每个链接,例如:
# for url in href_list:
# driver.get(url)
# # ... 解析详情页
except Exception as e:
print(f"执行出错:{e}")
finally:
driver.quit()⚠️ 重要注意事项:
- 类名含空格 → 必须用 XPath:CSS 选择器 .programme.titles 表示同时具有两个类,而 "programme titles" 是单个类名(含空格),此时应使用 //h4[@class="programme titles"] 或更鲁棒的 //h4[contains(@class,"programme") and contains(@class,"titles")]。
- 显式等待优于 time.sleep():presence_of_all_elements_located 确保所有匹配元素已渲染完成,避免因加载延迟导致漏抓。
- 防御性编程:get_attribute("href") 可能返回 None(如链接未加载完成或被 JS 动态移除),建议增加 if elem.get_attribute("href") 过滤。
- 反爬提示:部分网站会检测 Selenium 特征,如需绕过,可添加 options.add_argument("--disable-blink-features=AutomationControlled") 并隐藏 navigator.webdriver(需额外 JS 注入)。
掌握此方法后,您不仅能稳定提取目标链接列表,还可轻松扩展至其他属性(如 text、data-*)或结合 BeautifulSoup 进行深度解析。核心逻辑始终是:结构化定位 → 显式等待 → 安全提取 → 异常防护。
立即学习“Python免费学习笔记(深入)”;










