You need to enable JavaScript to run this app. Python网页爬虫问题:如何编写调用函数并输出字典格式结果
优惠活动
大模型
产品
解决方案
定价
更多

Python网页爬虫问题:如何编写调用函数并输出字典格式结果

问题修复方案

你代码中存在3类核心问题:

  • 调用错误:末尾的函数调用缺少下划线,get stories()应为get_stories(),这是函数无法正常触发的直接原因
  • 基础配置错误:headers字典缺少User-Agent键,且请求时没有传入headers参数;base_url缺少https前缀,直接请求会报错
  • 变量使用不规范:用全局变量存储结果可读性差,建议调整为函数返回值形式,方便后续调用

修正后的完整代码如下:

from bs4 import BeautifulSoup
import requests

def get_stories():
    """爬取目标站点热点新闻,返回字典列表格式的结果"""
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36'
    }
    base_url = 'https://www.example.com' # 补全http协议前缀
    source = requests.get(base_url, headers=headers).text # 传入headers参数
    soup = BeautifulSoup(source, 'html.parser')
    articles = soup.find_all("article", class_="card")
    print(f"Number of articles found: {len(articles)}")
    top_stories = [] # 把存储结果的列表挪到函数内部,避免全局变量污染
    for article in articles:
        try:
            headline = article.h3.text.strip()
            link = base_url + article.a['href']
            text = article.find("div", class_="field--type-text-with-summary").text.strip()
            img_url = base_url + article.picture.img['data-src']
            # 直接构造字典存入列表
            stories_dict = {
                'Headline': headline,
                'Link': link,
                'Text': text,
                'Image': img_url
            }
            top_stories.append(stories_dict)
        except AttributeError as ex:
            print('Error:',ex)
    return top_stories # 函数返回结果

# 正确调用函数,拿到字典格式的结果
if __name__ == '__main__':
    result = get_stories()
    # 此时result就是每个元素为单条新闻字典的列表,可直接使用
    # 如果需要整合成一个大字典,可按如下方式调整(以新闻标题为键为例):
    result_dict = {item['Headline']:item for item in result}
    print(result_dict)

如果你需要单条新闻的字典格式,直接遍历result即可拿到每条对应的字典;如果需要所有数据存在同一个大字典里,可参考代码中的result_dict构造方式,自行选择键值规则即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 17:36:07