簡體   English   中英

如何從具有非結構化表的文本文檔中獲取值

[英]How to get a value from a text document that has an unstructured table

我正在嘗試從10-K文本文件中獲取total assets值。 問題是html格式因一家公司而異。

Apple 10-K為例:總資產在具有balance sheet標題的表中,並且該表的某些行中存在現金,存貨等典型術語。 在最后一行中,2015年的資產總計為290,479,2014年的資產總計為231,839。我想獲得2015年的資產-> 290,479。 我一直無法找到一種方法

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

在此處輸入圖片說明

使用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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM