2017-10-17 25 views
0

pythonのWebスクラップに関するクローズ・アップ・ノウの知識。PythonでWebページからテーブルを取得

私はthisページからテーブルを取得する必要があります:

http://performance.morningstar.com/funds/etf/total-returns.action?t=IWF 

私が興味の表は、このです:これはどのような私です enter image description here (テーブルの上のチャートを無視)

現在:

from selenium import webdriver 
from bs4 import BeautifulSoup 

# load chrome driver 
driver = webdriver.Chrome('C:/.../chromedriver_win32/chromedriver') 

# load web page and get source html 
link = 'http://performance.morningstar.com/funds/etf/total-returns.action?t=IWF' 
driver.get(link) 
html = driver.page_source 

# make soup and get all tables 
soup = BeautifulSoup(html, 'html.parser') 
tables = soup.findAll('table',{'class':'r_table3'}) 
tbl = tables[1] # ideally we should select table by name 

ここからはどこに進んでいますか?ので、ここで

+0

あなたはBeautifulSoupとセレンの両方を使用している具体的な理由はありますか? – Goralight

+0

私は、ページがJavaScriptで埋め込まれているときに、最初に読み込んでからbeautifulsoupを解析する必要があると言われましたか? –

+0

私はそれが問題であると言っているわけではありませんでした。あなたがそれを必要とした理由に骨が欠けていました。あなたはテーブル全体が必要ですか?または特定の細胞ですか? – Goralight

答えて

1

Total Return %  1-Day 1-Week 1-Month 3-Month YTD 1-Year 3-Year 5-Year 10-Year 15-Year 
IWF (Price) 0.13 0.83 2.68 5.67 23.07 26.60 15.52 15.39 8.97 10.14 
IWF (NAV) 0.20 0.86 2.66 5.70 23.17 26.63 15.52 15.40 8.98 10.14 
S&P 500 TR USD (Price) 0.18 0.52 2.42 4.52 16.07 22.40 13.51 14.34 7.52 9.76 
+0

コードを実行しましたか?もしそうなら、あなたのフィードバックは何ですか?あなたはそのテーブルからデータを取得していませんか? – SIM

0

OK、私はそれをやった方法は次のとおりです。

from selenium import webdriver 
from bs4 import BeautifulSoup 

# load chrome driver 
driver = webdriver.Chrome('C:/.../chromedriver_win32/chromedriver') 

# load web page and get source html 
link = 'http://performance.morningstar.com/funds/etf/total-returns.action?t=IWF' 
driver.get(link) 
html = driver.page_source 

# make soup and get table 
soup = BeautifulSoup(html, 'html.parser') 
tables = soup.find_all('table',{'class':'r_table3'}) 
tbl = tables[1] # ideally we should select table by name 

# column and row names 
rows = tbl.find_all('tr') 
column_names = [x.get_text() for x in rows[0].find_all('th')[1:]] 
row_names = [x.find_all('th')[0].get_text() for x in rows[1:]] 

# table content 
df = pd.DataFrame(columns=column_names, index=row_names) 
for row in rows[1:]: 
    row_name = row.find_all('th')[0].get_text() 
    df.ix[row_name] = [column.get_text() for column in row.find_all('td')] 
print(df) 

よりエレガントな方法は、すなわち、等の列と行をループせずに、ありますが、私は既製のメソッドを呼び出すことができますか?

from selenium import webdriver 
from bs4 import BeautifulSoup 
import time 

driver = webdriver.Chrome() 
link = 'http://performance.morningstar.com/funds/etf/total-returns.action?t=IWF' 
driver.get(link) 
time.sleep(3) 

soup = BeautifulSoup(driver.page_source, 'lxml') 
driver.quit() 

tab_data = soup.select('table')[1] 
for items in tab_data.select('tr'): 
    item = [elem.text for elem in items.select('th,td')] 
    print(' '.join(item)) 

部分的な結果:あなたはこのように行くことができるWebページからデータを取得するには

関連する問題