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

使用Beautiful Soup爬取URL时无法获取全部链接如何解决

问题解决方法

问题原因

你现有代码中直接使用link.a的写法只会返回当前节点下匹配到的第一个<a>标签,因此只能拿到第一条URL。要获取所有目标链接,需要在定位到内容容器后,查找容器内全部符合条件的<a>标签。

修改后可运行代码

from bs4 import BeautifulSoup

# 打开本地html文件,指定编码避免乱码
with open("mainLocalFile.html", encoding="utf-8") as fp:
    soup2 = BeautifulSoup(fp, 'html.parser')
    # 定位到目标内容的外层容器
    content_container = soup2.find('div', class_='blockSpoiler-content')
    # 查找容器内所有带rel="external"属性的a标签,过滤无关内容
    target_links = content_container.find_all('a', rel="external")
    # 遍历提取href属性值
    for link in target_links:
        print(link.get('href'))

代码说明

  • 使用find_all('a', rel="external")可以精准匹配所有你需要的目标链接标签,避免抓取到页面其他位置的无关链接
  • 用link.get('href')代替link['href']容错性更高,即使遇到没有href属性的a标签也不会报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:48:04