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

使用BeautifulSoup调用split报错:'NoneType'对象不可调用

解决TypeError: 'NoneType' object is not callable问题

错误原因

  1. BeautifulSoup find方法参数格式错误:你写的match.find({'div': {'class': 'matchDayHeadline'}})不符合find方法的参数规范,正确写法需要明确指定标签名和对应的属性,错误的参数格式会导致find找不到目标元素,返回None。
  2. 未做非空判断:即便参数格式正确,也可能存在部分upcomingMatchesSection区块里没有matchDayHeadline元素的情况,直接对None调用split()就会触发报错。

修复方案

  1. 修正find方法的参数,使用标签+属性的正确匹配方式;
  2. 先判断目标元素是否存在,再调用split()方法;
  3. 针对找不到元素的情况添加兜底逻辑。

修复后的代码:

def get_parsed_page(url, delay=0.5):
    data = solver.request_get(url)
    return BeautifulSoup(data.solution.response, "lxml")

def get_matches():
    global MATCH_WITH_COUNTDOWN
    matches = get_parsed_page("https://****/matches/")
    matches_list = []

    matchdays = matches.find_all("div", {"class": "upcomingMatchesSection"})
    for match in matchdays:
        matchDetails = match.find_all("div", {"class": "upcomingMatch"})
        # 修正find参数格式,先获取目标元素
        headline_elem = match.find("div", class_="matchDayHeadline")
        if headline_elem:
            # 先获取元素文本再调用split
            date = headline_elem.get_text().split()[-1]
            # 可根据需求将date加入matches_list或做其他处理
        else:
            # 处理找不到元素的情况,比如设默认值或跳过
            date = None
            print("当前区块未找到matchDayHeadline元素")

补充说明

  • find("div", class_="matchDayHeadline") 和 find("div", {"class": "matchDayHeadline"}) 两种写法都有效,前者是更简洁的语法;
  • 必须先调用get_text()获取元素的文本内容,再对文本执行split(),这是更规范的处理方式;
  • 加入非空判断后,代码遇到缺失元素的情况不会中断,能继续执行后续逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 04:50:02