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

Python中如何将变量存储的文本转换为BeautifulSoup对象

修复方案

你当前代码的问题是直接打印BeautifulSoup返回的p标签对象会输出完整的HTML标签结构,而非标签内的纯文本内容,只需调整提取文本的方法即可实现需求。

修复后完整代码

for i in range(self.length):
    print(colored('Title', 'green', attrs=['bold']))
    print(self.url.entries[i].title)
    print(colored('Link', 'green', attrs=['bold']))
    print(self.url.entries[i].link)
    print(colored('Description', 'green', attrs=['bold']))
    soup = BeautifulSoup(self.url.entries[i].summary, 'html.parser')
    for s in soup.find_all('p'):
        # get_text()提取标签内部纯文本,strip=True清理首尾多余空白字符
        print(s.get_text(strip=True))

补充说明

如果单条summary里包含多个p标签,需要把所有内容合并为一段输出,可以替换循环写法为:

p_texts = [s.get_text(strip=True) for s in soup.find_all('p')]
print('\n'.join(p_texts))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:33:02