Python去除HTML标签时报expected string or bytes-like object如何解决
问题根因
你拿到的raw_html是bs4.element.ResultSet类型,本质是BeautifulSoup查询返回的标签对象列表,不是字符串,所以正则替换、直接传入BeautifulSoup解析都会触发「expected string or bytes-like object」类型错误。
解决方法
不需要额外转字符串、用正则二次解析,直接遍历ResultSet里的每个标签对象提取文本即可:
# 方法1:直接提取所有div的文本,逐行拼接 output = [] for div_tag in raw_html: # get_text()可直接提取标签内的纯文本 output.append(div_tag.get_text()) final_text = '\n'.join(output) print(final_text)
运行后就会输出你要的格式:
A financial model should be developed when the business planning process has reached the _______ planning stage The correct answer is: Operational Selling new products to existing customers is a strategy of The correct answer is: Product development In the strategic review and strategic planning process Product/Portfolio Analysis follows immediately after the The correct answer is: Industry and competitor analysis
如果需要只输出单组题目+答案,按需切片取列表元素即可:
# 只取第一组题目和答案 first_q = raw_html[0].get_text() first_a = raw_html[1].get_text() print(f"{first_q}\n{first_a}")
内容的提问来源于stack exchange,提问作者adiletgov
相关产品推荐
相关产品推荐

