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

为何添加if判断仍触发AttributeError?Beautiful Soup爬取疑问

问题原因与解决办法

你的错误核心是判断逻辑顺序错了:当某个table_row里没有<a>标签时,table_row.a会返回None。而你写的if table_row.a.text is not None,是先尝试获取table_row.a.text,再判断是否为None——但这时候table_row.a已经是None了,调用它的.text属性直接就触发了AttributeError,根本轮不到判断那一步。

正确的写法应该是先检查table_row.a是否存在(即不为None),再去访问它的.text属性:

for i, table_row in enumerate(df_tr): 
    if table_row.a is not None: 
        print(table_row.a.text) 

或者更严谨一点,可以用BeautifulSoup提供的get_text()方法(即使标签不存在也不会报错,返回空字符串):

for i, table_row in enumerate(df_tr): 
    text = table_row.a.get_text(strip=True) if table_row.a else ""
    if text:
        print(text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:10:35