2016-09-02 40 views
0
from bs4 import BeautifulSoup 
import urllib2 
import re 
import json 
p = """ 
<thead> 
<tr> 
<th>Company Name</th> 
<th>Symbol</th> 
<th>Market</th> 
<th>Price</th> 
<th>Shares</th> 
<th>Offer Amount</th> 
<th>Date Priced</th> 
</tr> 
</thead> 
<tr> 
<td><a href="http://www.nasdaq.com" id="two">EXFO INC.</a></td> 
<td><a href="http://www.nasdaq.com" id="two">EXFO</a></td> 
<td><a href="http://www.nasdaq.com" id="two">NASDAQ</a></td> 
<td>$26</td> 
<td>7,000,000</td> 
<td>$182,000,000</td> 
<td>6/30/2000</td> 
</tr> 
<tr> 
<td><a href="http://www.nasdaq.com">IGO, INC.</a></td> 
<td><a href="http://www.nasdaq.com" id="two">MOBE</a></td> 
<td><a href="http://www.nasdaq.com" id="two">NASDAQ</a></td> 
<td>$12</td> 
<td>4,000,000</td> 
<td>$48,000,000</td> 
<td>6/30/2000</td> 
</tr>""" 
soup = BeautifulSoup(p, 'html.parser') 
for ana in soup.find_all('td'): 
    if ana.parent.name == 'tr': 
    print ana.string 

こんにちは!私は1つのサイトからいくつかのデータをcsvファイルに書き込もうとしています。望ましい結果は?私はちょうど置く方法がわからない、私はBeautifulSoupを使用して子供タグの結果をCSVファイルに書き込む

EXFO INC. 
EXFO 
NASDAQ 
$26 
7,000,000 
$182,000,000 
6/30/2000 
IGO, INC. 
MOBE 
NASDAQ 
$12 
4,000,000 
$48,000,000 
6/30/2000 

任意のアイデアはどのようにこれを行うには、次の今印刷きているために行うことを学んだ何

EXFO INC.,EXFO,NASDAQ,$26,7,000,000,$182,000,000,6/30/2000 
IGO, INC.,MOBE,NASDAQ, $12, 4,000,000,$48,000,000,6/30/2000 

とcsvファイルでありますそれをすべてループに入れ、すべてのタグ ""をすべて抽出します。

+0

私はすべてのタグtrがすべてのtdタグを抽出することを意味しました。 –

答えて

0

thead要素番目のタグを見つけ、テーブルを選択し、他のすべての行を抽出し、TDテキストを書き、次に書く:

from bs4 import BeautifulSoup 
from csv import writer 

soup = BeautifulSoup(html) 
table = soup.select_one("table") 
with open("out.csv", "w") as f: 
    wr = writer(f) 
    wr.writerow([th.text for th in table.select("thead th")]) 
    for row in table.find_all("tr"): 
     data = [td.text for td in row.find_all("td")] 
     if data: 
      wr.writerow(data) 

あなたを与えることになる:

Company Name,Symbol,Market,Price,Shares,Offer Amount,Date Priced 
EXFO INC.,EXFO,NASDAQ,$26,"7,000,000","$182,000,000",6/30/2000 
"IGO, INC.",MOBE,NASDAQ,$12,"4,000,000","$48,000,000",6/30/2000 

もう1つの方法は、すべてtrのとインデックス/スライス:

from bs4 import BeautifulSoup 
from csv import writer 
soup = BeautifulSoup(html) 

rows = soup.select("table tr") 
with open("out.csv", "w") as f: 
    wr = writer(f) 
    wr.writerow([th.text for th in rows[0].find_all("th")]) 
    for row in rows[1:]: 
     data = [td.text for td in row.find_all("td")] 
     wr.writerow(data) 

どのようなアプローチは、あなたが行にグループに各TR内のデータを、関連するすべてのTDタグを抽出することができますように、すべてのTRタグを通過します。

+0

広範な答えをありがとう。それは私を助けてくれました! –

関連する問題