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

使用BeautifulSoup遍历已找到元素打印链接时遇AttributeError,如何解决?

问题解决:BeautifulSoup遍历卡片获取链接报错

错误原因

你用soup.find_all()得到的cards是元素列表(ResultSet对象),不能直接对整个列表调用.find_all()方法,必须逐个处理列表里的每一个卡片元素,再在单个卡片内查找链接。

修正后的代码

from bs4 import BeautifulSoup

with open("index.html") as fp:
    soup = BeautifulSoup(fp, 'html.parser')

cards = soup.find_all('div', attrs={'class': 'up-card-section'})

print(len(cards))

# 遍历每个卡片元素,而非直接对cards列表调用find_all
for card in cards:
    # 在单个卡片里查找所有a标签
    for link in card.find_all('a'):
        print(link.get('href'))

补充提示

如果每个卡片仅包含一个链接,可将card.find_all('a')替换为card.find('a'),直接获取href:

for card in cards:
    link = card.find('a')
    if link:  # 避免卡片无链接时报错
        print(link.get('href'))

内容的提问来源于stack exchange,提问作者code-8

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:25:18