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

如何用Python的Selenium获取指定div内的所有链接

获取class为rec_view的div内所有链接的方法

这里给你两种常用的解决方案,分别适配不同的使用场景:

前端浏览器环境(JavaScript)

如果是在网页前端直接处理这段DOM结构,可以用原生JavaScript快速实现:

// 定位到目标div元素
const targetDiv = document.querySelector('.rec_view');
// 获取div内部所有的<a>标签
const linkElements = targetDiv.querySelectorAll('a');
// 将NodeList转为数组并提取每个链接的href属性
const allLinks = Array.from(linkElements).map(link => link.href);

// 打印结果,也可以根据需求做其他业务处理
console.log(allLinks);

执行后会得到一个包含所有目标链接的数组:["www.xyz.com/firstlink.html", "www.xyz.com/seclink.html", "www.xyz.com/thrdlink.html"]

后端数据处理/爬虫场景(Python + BeautifulSoup)

如果你是在后端处理HTML字符串(比如爬虫抓取到的页面内容),可以用BeautifulSoup库来解析:

首先需要安装依赖:

pip install beautifulsoup4

然后编写处理代码:

from bs4 import BeautifulSoup

# 你的HTML内容
html_str = """
<div class="rec_view"> 
<a href='www.xyz.com/firstlink.html'> <img src='imga.png'> </a> 
<a href='www.xyz.com/seclink.html'> <img src='imgb.png'> </a> 
<a href='www.xyz.com/thrdlink.html'> <img src='imgc.png'> </a> 
</div>
"""

# 解析HTML
soup = BeautifulSoup(html_str, 'html.parser')
# 找到class为rec_view的div
rec_view_div = soup.find('div', class_='rec_view')
# 提取所有<a>标签的href属性(用get方法避免属性不存在时报错)
link_list = [a.get('href') for a in rec_view_div.find_all('a')]

# 输出结果
print(link_list)

运行这段代码后,同样会得到包含所有目标链接的列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:38:47