【问题标题】:Python - remove markup tags and read html from the file?Python - 删除标记标签并从文件中读取 html?
【发布时间】:2017-10-10 17:53:32
【问题描述】:

我有一个名为 BBC_news_home.html 的文件,我需要删除所有标记标签,所以我剩下的只是一些文本。到目前为止,我得到了:

def clean_html(html):
    cleaned = ''

line = html

pattern = r'(<.*?>)'

result = re.findall(pattern, line, re.S)

if result:
    f = codecs.open("BBC_news_home.html", 'r', 'utf-8')
    print(f.read())
else:
    print('Not cleaned.')
return cleaned

我已与 regex101.com 确认该模式是否正确我只是不确定如何打印输出以检查标记标签是否消失?

【问题讨论】:

标签: python html text information-retrieval data-extraction


【解决方案1】:

你真的应该为此使用 BeautifulSoup。根据您需要的 python 版本执行pip3 install BeautifulSoup4pip install BeautifulSoup4。我已经发布了一个类似问题的答案here。为了完整起见:

from bs4 import BeautifulSoup

def cleanme(html):
    soup = BeautifulSoup(html) # create a new bs4 object from the html data loaded
    for script in soup(["script"]): 
        script.extract()
    text = soup.get_text()
    return text
testhtml = "<!DOCTYPE HTML>\n<head>\n<title>THIS IS AN EXAMPLE </title><style>.call {font-family:Arial;}</style><script>getit</script><body>I need this text captured<h1>And this</h1></body>"

cleaned = cleanme(testhtml)
print (cleaned)

结果的输出将仅仅是I need this text captured And this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2019-03-30
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2013-12-21
    相关资源
    最近更新 更多