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

替换列表中>符号时触发TypeError: 'NoneType' object is not callable错误

问题:替换BeautifulSoup结果中的">"符号时报错

我想用以下代码把列表里的所有">"替换成空格:

import requests
from bs4 import BeautifulSoup

response = requests.get('https://www.holidayscalendar.com/')
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
block = soup.find_all("td", class_="wphc-tbl-name")

for i in range(len(block)):
    block[i] = block[i].replace(">", " ")
    print(block)

运行后程序崩溃,抛出错误:

TypeError: 'NoneType' object is not callable

我尝试改用变量间接操作,问题仍未解决:

for i in range(len(block)):
    block_1 = block[i]
    block_1.replace(">", " ")
    print(block_1)

问题原因

soup.find_all()返回的是BeautifulSoup的Tag对象列表,而非普通字符串。直接对Tag对象调用replace()方法会出错——Tag本身没有这个字符串方法,这是API使用错误。

解决方案

需要先将Tag对象转换为字符串,或提取其中的文本内容后再执行替换:

方案1:提取文本内容后替换(仅保留文本)

如果只需要Tag里的纯文本,用.get_text()提取文本再替换:

import requests
from bs4 import BeautifulSoup

response = requests.get('https://www.holidayscalendar.com/')
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
block = soup.find_all("td", class_="wphc-tbl-name")

for tag in block:
    cleaned_text = tag.get_text().replace(">", " ")
    print(cleaned_text)

方案2:转换整个Tag为字符串后替换(保留HTML结构)

如果需要保留原HTML结构,仅替换字符串中的">",先将Tag转为字符串再处理:

import requests
from bs4 import BeautifulSoup

response = requests.get('https://www.holidayscalendar.com/')
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
block = soup.find_all("td", class_="wphc-tbl-name")

for tag in block:
    tag_str = str(tag)
    cleaned_str = tag_str.replace(">", " ")
    print(cleaned_str)

额外提示

  • 避免用for i in range(len(block))遍历列表,直接遍历元素更简洁且不易出错。
  • 原代码的核心错误是混淆了BeautifulSoup Tag对象与普通字符串的方法差异。

内容的提问来源于stack exchange,提问作者Ашот Какой а

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:06:02