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

爬取CNN网页链接触发AttributeError:ResultSet对象无find_all属性

问题分析与解决

错误原因

你的代码里有两个关键问题引发了报错:

  1. 错误调用BeautifulSoup实例:soup(response)这种写法是把soup对象当成函数调用,等价于soup.find_all(response),会返回一个ResultSet(元素列表),而ResultSet本身没有find_all方法,因此触发AttributeError。正确做法是直接在soup实例上调用find_all。
  2. 打印逻辑错误:最后循环里print(links)会把整个链接列表重复打印多次,应该打印单个链接link。

修正后的代码

import requests
from bs4 import BeautifulSoup

url = "https://www.cnn.com/"

response = requests.get(url)
# 先检查请求是否成功
if response.status_code == 200:
    soup = BeautifulSoup(response.text, "html.parser")
    links = []
    # 直接在soup实例上调用find_all方法
    for link in soup.find_all("a", href=True):
        links.append(link["href"])
    # 循环打印单个链接
    for link in links:
        print(link)
else:
    print(f"请求失败,状态码:{response.status_code}")

额外提示

  • 加入请求状态码检查可以避免请求失败后后续代码无意义执行。
  • 爬取网站前请遵守目标网站的robots.txt规则及相关法律法规。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:31:40