如何解决清除变量中HTML标签时出现的TypeError错误?
解决清除HTML标签时的TypeError问题
错误原因
TypeError: expected string or bytes-like object 是因为传给cleanhtml函数的变量不是字符串/字节类型——比如你可能直接把网页解析库(如BeautifulSoup)返回的Tag对象传进去了,而正则re.sub只接受字符串或字节作为输入。
解决方法
方法1:修正现有正则函数,确保输入为字符串
在函数里先将输入转为字符串,再执行正则替换,同时优化多余空格的处理:
import re # 预编译正则表达式,提升效率 CLEANR = re.compile('<.*?>') def cleanhtml(raw_html): # 先将输入转为字符串,兼容非字符串类型的输入 if not isinstance(raw_html, str): raw_html = str(raw_html) # 移除所有HTML标签 cleantext = re.sub(CLEANR, '', raw_html) # 合并多余的空格、换行符,并去除首尾空白 cleantext = re.sub('\s+', ' ', cleantext).strip() return cleantext
方法2:用BeautifulSoup更可靠地清理HTML
正则处理HTML容易出现嵌套标签、特殊标签漏处理的问题,推荐用专业的HTML解析库BeautifulSoup:
from bs4 import BeautifulSoup def cleanhtml_with_bs(raw_html): # 确保输入为字符串 if not isinstance(raw_html, str): raw_html = str(raw_html) # 解析HTML并提取纯文本 soup = BeautifulSoup(raw_html, "html.parser") # 提取文本时自动处理空白,用指定分隔符连接 return soup.get_text(strip=True, separator=', ')
测试示例
用你提供的HTML内容测试:
html_content = '<td><a class="css-zwebxb" href="/players/1093743350">Zero Two</a></td>, <td><time datetime="PT2M5.031S" time="1670072352910" title="Saturday, December 3, 2022 12:57 PM">00:02</time></td>, <td class="css-7a8yo0"> <button class="css-sanbnz" type="button"><i class="glyphicon glyphicon-flag"></i></button></td>' # 方法1输出:Zero Two, 00:02, print(cleanhtml(html_content)) # 方法2输出:Zero Two, 00:02, print(cleanhtml_with_bs(html_content))
内容的提问来源于stack exchange,提问作者Japanator 14
相关产品推荐
相关产品推荐

