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

2024-10-04 09:18:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

content对象包含“p”标记中页面的所有主文本,但是在输出中仍然存在其他标记,如下图所示。我要删除包含在匹配的标记对中的所有字符以及标记本身。只剩下文字了。

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

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

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

enter image description here


Tags: 方法代码标记com网站examplewwwpage
3条回答

您需要使用strings generator

for text in content.strings:
   print(text)

使用正则表达式:

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)

你可以用^{}

for i in content:
    print i.get_text()

下面的示例来自docs

>>> 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'

相关问题 更多 >