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

标签 python html string parsing beautifulsoup

我正在尝试使用带有以下代码的 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('>')))

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

enter image description here

最佳答案

使用正则表达式:

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

使用 BeautifulSoup:(来自 here 的解决方案)

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)

关于Python,从字符串中删除所有html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37018475/

相关文章:

python - python中类 block 和函数 block 的区别

C - 包含整数和字符串的文件(除法问题)

python - 使用 PyBluez 编写 HID 服务

python - 基于类的 View 中的可选 url 参数

javascript - 如何使用 Javascript 或 jQuery 在 TinyMCE 编辑器中获取 HTML 元素节点值

html - 在屏幕尺寸上显示内容

Java println(charArray + String) 与 println(charArray)

c++ - GCC 下的简单 C++ 字符串格式化

python - 为什么 numpy 的 where 操作比 apply 函数快?

html - Facebook 情绪