python - 如何从输出文本中删除 HTML 标签?

标签 python html

如果之前已经有人问过这个问题,我深表歉意,但我尝试过的所有解决方案似乎都不起作用。

我创建了一个程序,用户可以在其中输入单词,该程序会从 Dictionary.com 网站中提取该单词的示例。

我想删除始终围绕关键字的 HTML 标记。我该如何去做呢?

import requests

word = input("Enter a word: ")

webContent = requests.get('https://www.dictionary.com/browse/'+word)

from bs4 import BeautifulSoup
soup = BeautifulSoup(webContent.text, 'html.parser')

results = soup.find_all('p', attrs={'class':'one-click-content css-it69we e15kc6du7'})

firstResult = results[0]
print(firstResult.contents[0:3])

结果: Result

最佳答案

import requests
import re

word = input("Enter a word: ")

webContent = requests.get('https://www.dictionary.com/browse/'+word)

from bs4 import BeautifulSoup
soup = BeautifulSoup(webContent.text, 'html.parser')

results = soup.find_all('p', attrs={'class':'one-click-content css-it69we e15kc6du7'})

firstResult = results[0]
firstResult.contents=[re.sub('<[^<]+?>', '', str(x)) for x in firstResult.contents]
print(firstResult.contents[0:3])

结果:

enter image description here

关于python - 如何从输出文本中删除 HTML 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53887905/

相关文章:

php - 通过 preg_match_all PHP 函数从 html 代码字符串中提取 img 标签

JavaScript 错误 : ReferenceError: edit is not defined edit(this);

python - 提取具有混合元素类型的表数据

python - 如何将 SVG 与 pygame 一起使用(或者以更高的清晰度显示 PNG)?

python - 在 django 中重新启动 postgres 连接

python - Numpy 内存错误创建巨大的矩阵

python - 如何从列表中的列表中绘制日期和小数?

javascript - 边框仅在切换事件后显示

html - word-wrap:break-word css 属性在 IE8 标准模式下不起作用

html - 如何在 div 保持不变的情况下将文本包装在 div 中?