2017-11-25 35 views
0

これは事実ですが、私はBeautifulSoupを使ってSECデータベースからデータを抽出しようとしていますが、私は文字通りPythonでは初めてですが、次のコードを書くことができました。BeautifulSoupを使用してspan要素のテキストを抽出する

アイデアは、.txtに引用符のリストを使用し、後で使用するために各会社の「CIK」番号を抽出することです。

import requests 
from bs4 import BeautifulSoup 
list_path = r"C:\Users\User1\Downloads\Quote list.txt" 

with open(list_path, "r") as flist: 
    for quote in flist: 
     quote = quote.replace("\n", "") 
     url = (r"https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=" + quote + 
     r"&type=10&dateb=&owner=exclude&count=100") 
     source_code = requests.get(url) 
     plain_text = source_code.text 
     soup = BeautifulSoup(plain_text, "html.parser") 
     for company_info in soup.find_all("span", {"class" :"companyName"}): 
      cik_code = company_info.string 
      print(cik_code) 

ここまでのコードでは、文字列 'cik_code'の値は「none」と表示されています。 HTMLの要素は以下の通りです:0000824142、直前に「(すべての会社の提出書類を参照してください)」私は、文字列cik_code

にその数を設定するにはどうすればよい

<span class="companyName dm-selected dm-test"> 
     AAON INC 
     <acronym title="Central Index Key">CIK</acronym> 
     #: 
     <a href="/cgi-bin/browse-edgar? 
     action=getcompany&amp;CIK=0000824142&amp;owner=exclude&amp;count=100" 
     class="">0000824142 (see all company filings)</a> 
</span> 

CIKコードは、最後の番号です

答えて

0

<span>タグの内側にある<a>タグに入るだけでいいと思います。

for company_info in soup.find_all('span', {'class': 'companyName'}): 
    cik_code = company_info.find_next('a').text.split(' ', maxsplit=1)[0] 
    print(cik_code) 

説明:

  • company_info.find_next('a')戻り値:
<a href="/cgi-bin/browse-edgar? 
    action=getcompany&amp;CIK=0000824142&amp;owner=exclude&amp;count=100" 
    class="">0000824142 (see all company filings)</a> 
  • .text戻り値:
0000824142 (see all company filings) 
  • .split(' ', maxsplit=1)[0]リターン:

0000824142

+0

私はなぜ知らないにもかかわらず、完全に働きました。ありがとう兄貴! –

+0

あなたに良いアイデアを与えるために説明を追加しました。 – Jay

関連する問題