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

BeautifulSoup搭配正则回调函数运行时报NoneType错误该如何解决?

报错原因

  • 错误调用不存在的方法:BeautifulSoup 中的Tag对象没有attr()方法,你尝试调用该方法获取href属性的逻辑本身就会触发异常;
  • 未做属性存在校验:页面中大量标签没有href属性,直接取值会返回None,将None传入re.search方法会触发参数类型不匹配的报错。

修复后可运行代码

import requests
from bs4 import BeautifulSoup
import re

webpage = requests.get('https://www.talkenglish.com/vocabulary/top-1500-nouns.aspx').content
soup = BeautifulSoup(webpage, "html.parser")

def has_how_to_use(tag):
    pattern = re.compile(r'\/how-to-use\/[a-zA-Z]+')
    # 先安全获取href属性,不存在则直接返回False
    href = tag.get('href')
    return href is not None and bool(re.search(pattern, href))

word_list = soup.find_all(has_how_to_use)

核心修改说明

  • 将错误的tag.attr('href')替换为tag.get('href'),这是BeautifulSoup官方提供的属性安全获取方法,属性不存在时会返回None而非直接抛出异常;
  • 新增href非空判断,仅存在href属性的标签才会进入正则匹配逻辑,避免None传入正则方法触发类型错误;
  • 正则字符串前添加r标记为原始字符串,避免转义符出现意料之外的解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:45:03