使用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
相关产品推荐
相关产品推荐

