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

首次使用Beautiful Soup出现Traceback报错,请求技术帮助

问题分析与解决方案

错误根源

你碰到的AttributeError: module 'collections' has no attribute 'Callable',核心原因是Python 3.10及以上版本已将Callable从collections模块迁移至collections.abc子模块,但你当前安装的Beautiful Soup 4版本未适配该变动,导致调用报错。

修复步骤

1. 升级Beautiful Soup到兼容版本

在命令提示符中执行以下命令,将bs4更新至适配Python 3.10+的最新版本:

pip install --upgrade beautifulsoup4

2. 修正代码缩进问题

你的代码中for循环后的print语句缺少缩进,这会引发语法错误,修正后的完整代码如下:

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')

# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
    print(tag.get('href', None))

验证方法

重新运行脚本,输入http://www.dr-chuck.com/page1.htm,此时应能正常提取并输出页面内所有锚点标签的href属性值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:10:52