Python,从字符串中删除所有html标签

新手上路,请多包涵

我正在尝试使用带有以下代码的 beautifulsoup 从网站访问文章内容:

 site= 'www.example.com'
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
content = soup.find_all('p')
content=str(content)

内容对象包含“p”标签内页面的所有主要文本,但是输出中仍然存在其他标签,如下图所示。我想删除包含在匹配的 < > 标签对和标签本身中的所有字符。这样就只剩下文字了。

我试过下面的方法,但似乎不起作用。

 ' '.join(item for item in content.split() if not (item.startswith('<') and item.endswith('>')))

删除字符串中子字符串的最佳方法是什么?以特定模式开始和结束,例如 < >

在此处输入图像描述

原文由 Mustard Tiger 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 667
2 个回答

你可以使用 get_text()

 for i in content:
    print i.get_text()

下面的示例来自 文档

 >>> markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
>>> soup = BeautifulSoup(markup)
>>> soup.get_text()
u'\nI linked to example.com\n'

原文由 JRodDynamite 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用正则表达式:

 re.sub('<[^<]+?>', '', text)

使用 BeautifulSoup:(解决方案来自 这里

 import urllib
from bs4 import BeautifulSoup

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text)

使用 NLTK:

 import nltk
from urllib import urlopen
url = "https://stackoverflow.com/questions/tagged/python"
html = urlopen(url).read()
raw = nltk.clean_html(html)
print(raw)

原文由 Ani Menon 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题