python - 从 HTML、CSS 和 JavaScript 中获取干净的字符串

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

目前,我正在尝试在 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)

最佳答案

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

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()

关于python - 从 HTML、CSS 和 JavaScript 中获取干净的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52189783/

相关文章:

python - 使用方法链接从同一数据帧中的多列中减去一列

python - 如何指定变量作为 re.sub 中的第一个参数

regex - 如何匹配不包含特定字符串的字符串

python - 生成器作为函数参数

python-3.x - 在 Python 3 中记录异常

python csv.dictreader 不使用 data.gov csv

python - 在 __init__ 中构造对象

python - 调试 asyncio 内存泄漏

java - 如何使用java从特定文件中获取所有姓名和出生日期

arrays - Matrix/2D-numpy 数组中的着色条目?