为何添加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
相关产品推荐
相关产品推荐

