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

使用BeautifulSoup爬取时遇AttributeError: ResultSet无findAll属性求助

解决BeautifulSoup中ResultSet没有findAll方法的错误

嘿,这个问题我太熟了!你碰到的AttributeError: ResultSet object has no attribute 'findAll',本质是把find_all(或findAll)返回的结果集(ResultSet,其实就是个标签列表)当成单个标签对象来操作了——ResultSet是多个标签的集合,它本身根本没有findAll方法,只有单个Tag元素才有这个能力。

我给你拆解两种常见场景的解决办法,直接套用就行:

场景1:先拿到一组容器,再从每个容器里提取链接

比如你想先定位到所有包含链接的div,再从每个div里抓a标签,错误写法会直接对ResultSet调用findAll,正确姿势是遍历每个容器元素:

from bs4 import BeautifulSoup
import requests

# 你的根URL,后续用来拼接相对路径
base_url = "https://your-root-domain.com"
target_url = "https://your-target-page.com"

response = requests.get(target_url)
soup = BeautifulSoup(response.text, "html.parser")

# 存储链接的字典
links_dict = {}

# 第一步:拿到所有包含链接的容器(这里以class为link-box的div为例)
link_containers = soup.find_all("div", class_="link-box")

# 第二步:遍历每个容器,对单个容器调用find_all提取a标签
for container_idx, container in enumerate(link_containers):
    # 对单个Tag对象调用find_all(推荐用find_all而非旧的findAll)
    a_tags = container.find_all("a")
    
    # 第三步:提取href并拼接根URL,存入字典
    for a_idx, a_tag in enumerate(a_tags):
        # 用get('href')更安全,避免a标签无href时抛出KeyError
        raw_href = a_tag.get("href")
        if raw_href:
            # 判断是否为完整URL,避免重复拼接根域名
            full_url = base_url + raw_href if not raw_href.startswith(("http://", "https://")) else raw_href
            # 用有意义的键存入字典,比如结合索引和链接文本
            link_key = f"link_{container_idx}_{a_tag.text.strip()}"
            links_dict[link_key] = full_url

场景2:直接提取页面中所有符合条件的a标签

如果不需要先定位容器,直接抓页面里所有a标签的href,那更简单:

links_dict = {}
all_a_tags = soup.find_all("a")

# 确保满足2个以上条目的要求
if len(all_a_tags) >= 2:
    for idx, a_tag in enumerate(all_a_tags):
        raw_href = a_tag.get("href")
        if raw_href:
            full_url = base_url + raw_href if not raw_href.startswith(("http://", "https://")) else raw_href
            links_dict[f"link_{idx}"] = full_url

几个关键注意点

  • 尽量用find_all替代旧的findAll,这是BeautifulSoup的官方推荐命名,更符合Python的PEP8规范;
  • 提取href时用a_tag.get('href')比a_tag['href']更稳妥,前者在标签无href属性时返回None,后者会直接抛出KeyError;
  • 拼接根URL一定要判断原始href是否已经是完整URL,不然会出现https://xxx.comhttps://yyy.com这种无效链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:27:09