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

使用BeautifulSoup获取href值报错ResultSet对象无find/find_all属性如何解决

BeautifulSoup报错问题修复方案

报错根本原因

你两次报错的核心原因一致:find_all() 方法返回的是 ResultSet对象(本质是元素列表),列表本身不存在find()或者find_all()方法,必须先遍历拿到列表里的单个标签元素,才能调用对应的查找、属性提取方法。

你代码的错误位置在for a_tag in article_cont.find('a'):这一行:
article_cont是你通过article.find_all('article')拿到的ResultSet列表,你没有遍历就直接调用了.find('a')方法,因此无论你把这里改成find还是find_all都会触发同类报错。

代码优化与修复

你不需要分三次遍历article_cont分别提取标题、日期、链接,单次遍历即可完成三个字段的提取,逻辑更简洁也不会触发报错,修正后代码如下:

import requests
from bs4 import BeautifulSoup as bs

titles = []
dates = []
links = []
page = 1
# 加请求头避免站点反爬拦截
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

while page <= 60:
    url = requests.get(f"http://detik.com/search/searchall?query=covid&siteid=2&sortby=time&page={page}", headers=headers)
    soup = bs(url.text, 'lxml')
    container = soup.find_all('div', class_='container content')
    for l_media in container:
        media_cont = l_media.find_all('div', class_='list media_rows list-berita')
        for article in media_cont:
            article_cont = article.find_all('article')
            # 单次遍历每个article标签,同时提取三个字段
            for item in article_cont:
                # 提取标题
                news_title = item.find('h2', class_='title')
                if news_title:
                    titles.append(news_title.text.strip())
                # 提取日期
                news_date = item.find('span', class_='date')
                if news_date:
                    dates.append(news_date.text.strip())
                # 提取链接
                a_tag = item.find('a')
                if a_tag and a_tag.has_attr('href'):
                    links.append(a_tag['href'])            
    page += 1

同类报错排查要点

  • 所有find_all()返回的结果都是可迭代的列表结构,必须遍历取到单个元素后,才能调用find()/find_all()、提取标签属性、获取文本等操作
  • 如果你要查找的页面节点全局唯一,可以直接用find()代替find_all(),拿到的就是单个标签对象,可直接调用后续方法
  • 提取文本、属性前增加非空判断,可以避免页面节点缺失时触发的空指针报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:36:03