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
相关产品推荐
相关产品推荐

