如何从具有非结构化表的文本文档中获取值

时间:2017-12-10 06:50:25

标签: python html regex beautifulsoup

我正在尝试从10-K文本文件中获取total assets值。问题是html格式因公司而异。

Apple 10-K为例: 总资产位于具有balance sheet标题的表格中,而现金,库存等典型字词存在于该表格的某些行中。在最后一行,2015年的资产总额为290,479,2014年为231,839。我想得到2015年的数字 - > 290479。

我无法找到方法

1)找到具有特定标题的相关表格(如资产负债表)和行中的单词(现金,......)

2)获取具有单词total assets的行中的值,并且属于更大的年份(2015年为我们的示例)。

import re
url = 'https://www.sec.gov/Archives/edgar/data/320193/000119312515356351/d17062d10k.htm'
r = requests.get(url)
soup = BeautifulSoup(r.text, "xml")
for tag in soup.find_all(text=re.compile('Total\sassets')):
            print(tag.findParent('table').findParent('table'))

enter image description here

1 个答案:

答案 0 :(得分:0)

使用lxmlhtml.parser代替xml我可以

title > CONSOLIDATED BALANCE SHEETS
row > Total assets
column 0 > Total assets
column 1 > 
column 2 > $
column 3 > 290,479
column 4 > 
column 5 > 
column 6 > $
column 7 > 231,839
column 8 > 

使用代码

import requests
from bs4 import BeautifulSoup
import re

url = 'https://www.sec.gov/Archives/edgar/data/320193/000119312515356351/d17062d10k.htm'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')# "lxml")

# get all `b` to find title
all_b = soup.find_all('b')
for item in all_b:
    # check text in every `b`
    title = item.get_text(strip=True)
    if title == 'CONSOLIDATED BALANCE SHEETS':
        print('title >', title)
        # get first `table` after `b`
        table = item.parent.findNext('table')
        # all rows in table
        all_tr = table.find_all('tr')
        for tr in all_tr:
            # all columns in row
            all_td = tr.find_all('td')
            # text in first column
            text = all_td[0].get_text(strip=True)
            if text == 'Total assets':
                print('row >', text)
                for i, td in enumerate(all_td):
                    print('column', i, '>', td.get_text(strip=True))
相关问题