【问题标题】:Get a clean string from HTML, CSS and JavaScript从 HTML、CSS 和 JavaScript 中获取干净的字符串
【发布时间】:2019-02-10 20:58:21
【问题描述】:

目前,我正在尝试在 sec.gov 上抓取 10-K 提交文本文件。

这是一个示例文本文件:
https://www.sec.gov/Archives/edgar/data/320193/000119312515356351/0001193125-15-356351.txt

文本文档包含 HTML 标记、CSS 样式和 JavaScript 等内容。理想情况下,我想在删除所有标签和样式后只抓取内容。

首先,我尝试了 BeautifulSoup 中显而易见的 get_text() 方法。那没有成功。
然后我尝试使用正则表达式删除 之间的所有内容。不幸的是,这也没有完全解决。它保留了一些标签、样式和脚本。

有没有人有一个干净的解决方案来实现我的目标?

到目前为止,这是我的代码:

import requests
import re

url = 'https://www.sec.gov/Archives/edgar/data/320193/000119312515356351/0001193125-15-356351.txt'
response = requests.get(url)
text = re.sub('<.*?>', '', response.text)
print(text)

【问题讨论】:

    标签: python regex python-3.x web-scraping


    【解决方案1】:

    让我们根据示例设置一个虚拟字符串:

    original_content = """
    <script>console.log("test");</script>
    <TD VALIGN="bottom" ALIGN="center"><FONT STYLE="font-family:Arial; ">(Address of principal executive offices)</FONT></TD>
    """
    

    现在让我们删除所有的 javascript。

    from lxml.html.clean import Cleaner # remove javascript
    
    # Delete javascript tags (some other options are left for the sake of example).
    
    cleaner = Cleaner(
        comments = True, # True = remove comments
        meta=True, # True = remove meta tags
        scripts=True, # True = remove script tags
        embedded = True, # True = remove embeded tags
    )
    clean_dom = cleaner.clean_html(original_content)
    

    (来自https://stackoverflow.com/a/46371211/1204332

    然后我们可以使用HTMLParser 库删除 HTML 标记(提取文本):

    from HTMLParser import HTMLParser
    
    # Strip HTML.
    
    class MLStripper(HTMLParser):
        def __init__(self):
            self.reset()
            self.fed = []
        def handle_data(self, d):
            self.fed.append(d)
        def get_data(self):
            return ''.join(self.fed)
    
    def strip_tags(html):
        s = MLStripper()
        s.feed(html)
        return s.get_data()
    
    text_content = strip_tags(clean_dom)
    
    print text_content
    

    (来自:https://stackoverflow.com/a/925630/1204332

    或者我们可以使用lxml 库获取文本:

    from lxml.html import fromstring
    
    print fromstring(original_content).text_content()
    

    【讨论】:

    • 我们在这里使用一个类的事实只是这个库(HTMLParser)的一个实现细节。您可以在此处查看文档:docs.python.org/2/library/htmlparser.html。正如您在他们的页面中看到的那样,他们就是这样做的。上课很方便,有空的时候看看。 :) 良好的编码,欢迎来到 Stack Overflow!
    • 我猜区别在于使用的解析器和方法。 lxml 是 C 库 libxml2libxslt 的绑定,HTMLParser 库是基于 Python 的解决方案,更简单。为了完整起见,我在答案中添加了lxml 选项。如果您只需要清理 HTML 标记,那么您也许可以只使用 HTMLParser。根据我的经验,lxml 通常是首选工具。但是我仍然使用HTMLParser 来删除 HTML 标签,因为它可以很好地完成工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 2020-11-02
    • 2012-08-26
    • 2011-05-25
    相关资源
    最近更新 更多