gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:12 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com