
本文详解如何使用Selenium高效获取页面内全部H2标签(特别是嵌套在结构中的)的可见文本及对应href属性,适用于多链接列表页(如总统演讲档案页),避免仅捕获首个元素的常见误区。
本文详解如何使用selenium高效获取页面内全部h2标签(特别是嵌套在`

本文详解如何使用Selenium高效获取页面内全部H2标签(特别是嵌套在结构中的)的可见文本及对应href属性,适用于多链接列表页(如总统演讲档案页),避免仅捕获首个元素的常见误区。
本文详解如何使用selenium高效获取页面内全部h2标签(特别是嵌套在`
在网页抓取实践中,常需批量提取具有统一结构的标题链接组——例如巴西前总统若泽·萨尔内演讲库页面中,每个演讲条目均以
Selenium 并无内置类似 BeautifulSoup 的 .find_all() 方法,但其 find_elements()(注意末尾为复数)完全可实现同等功能:它返回符合定位条件的所有 WebElement 对象列表,是批量提取的基石。
针对目标页面(http://www.biblioteca.presidencia.gov.br/https://www.php.cn/link/263b1243ca2dbeb358777ceabc4a2e4c),观察HTML结构可知:
以下是完整、健壮的实现代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# 配置浏览器选项(静默运行、禁用通知等)
options = Options()
options.add_argument("--disable-notifications")
options.add_experimental_option("excludeSwitches", ["enable-automation", "enable-logging"])
options.add_argument("--headless") # 可选:无头模式提升效率
driver = webdriver.Chrome(options=options)
wait = WebDriverWait(driver, 10)
try:
url = "http://www.biblioteca.presidencia.gov.br/presidencia/ex-presidentes/jose-sarney/discursos/1985?b_start:int=0"
driver.get(url)
# 显式等待:确保至少一个 .tileHeadline 元素可见(作为页面加载完成信号)
wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "tileHeadline")))
# ✅ 关键:使用 find_elements() 批量获取所有 h2 下的 a 标签
h2_links = driver.find_elements(By.CSS_SELECTOR, "h2 a")
# 结构化输出:每条记录包含 title 和 href
results = []
for idx, elem in enumerate(h2_links, 1):
title = elem.text.strip()
href = elem.get_attribute("href")
if href: # 过滤空链接
results.append({"title": title, "href": href})
print(f"[{idx}] {title}")
print(f" → {href}\n")
print(f"✅ 成功提取 {len(results)} 个H2链接条目。")
finally:
driver.quit()
通过该方案,你可稳定、可扩展地批量采集任意含结构化H2链接的页面数据,并轻松将结果存入列表、DataFrame或JSON文件,为后续解析、下载或分析奠定基础。
相关文章
Python3中如何使用Selenium Wire捕获浏览器后台XHR网络请求?
怎样在Python中编写脚本自动提取网页中的所有外部链接?
如何在动态下拉框中根据邮政编码选择街道选项
如何使用 Selenium Java 获取搜索结果数并断言其大于 5000
为什么Python3中某些旧版Pandas代码运行会报DepreciationWarning?
相关标签:
本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
相关专题
热门下载
相关下载
精品课程
共0课时 | 0人学习
共0课时 | 0人学习
最新文章