Warm tip: This article is reproduced from serverfault.com, please click

其他-如何使用python解析txt格式的html?

(其他 - how to use python to parse a html that is in txt format?)

发布于 2020-11-29 20:59:26

我正在尝试解析一个txt,例如下面的链接。txt格式为html。我想获取位于文件顶部的“ COMPANY CONFORMED NAME”,并且我的函数应返回“ Monocle Acquisition Corp”。 https://www.sec.gov/Archives/edgar/data/1754170/0001571049-19-000004.txt

我在下面尝试过:

import requests
from bs4 import BeautifulSoup

url = 'https://www.sec.gov/Archives/edgar/data/1754170/0001571049-19-000004.txt'
r = requests.get(url)
soup = BeautifulSoup(r.content, "html")

但是,“汤”根本不包含“公司符合名称”。有人可以指出我正确的方向吗?

Questioner
Lisa
Viewed
11
Luca Angioloni 2020-11-30 05:26:40

你要查找的数据不在HTML结构中,因此Beautiful Soup并不是最好的工具。正确,快速地搜索此数据的方法只是使用一个简单的正则表达式,如下所示:

import re
import requests

url = 'https://www.sec.gov/Archives/edgar/data/1754170/0001571049-19-000004.txt'
r = requests.get(url)
text_string = r.content.decode()

name_re = re.compile("COMPANY CONFORMED NAME:[\\t]*(.+)\n")

match = name_re.search(text_string).group(1)
print(match)