2014-11-06 86 views
2

我正試圖用雅虎金融與美麗的湯羹在Python中颳去道瓊斯股票指數。用Python篡改道瓊斯指數的雅虎財經

這是我曾嘗試:

from bs4 import BeautifulSoup 

myurl = "http://finance.yahoo.com/q/cp?s=^DJI" 
soup = BeautifulSoup(html) 

for item in soup: 
    date = row.find('span', 'time_rtq_ticker').text.strip() 
    print date 

下面是來自谷歌的鍍鉻元素檢查: enter image description here

如何,我只颳去跨度標籤17,555.47多少?

+1

你想學習如何使用BeautifulSoup刮,還是你只是感興趣的數據?如果你需要這些數據,我相信他們的[api](https://code.google.com/p/yahoo-finance-managed/wiki/YahooFinanceAPIs)可能是一個更好的來源。 – nerdwaller 2014-11-06 23:01:22

+0

我只是簡單地想從雅虎財經刮這一個數字。歡呼 – 2014-11-06 23:03:24

+0

由於您沒有聲明變量'html',因此您呼叫「soup = BeautifulSoup(html)」可能會返回一個錯誤。它應該讀取'myurl'而不是'html'嗎? – thefragileomen 2014-11-06 23:06:22

回答

3

只需使用find,確實很容易,就像這樣:

from bs4 import BeautifulSoup 
import requests 

myurl = "http://finance.yahoo.com/q/cp?s=^DJI" 
# I use requests to get the html content 
html = requests.get(myurl).content 
soup = BeautifulSoup(html) 

# you don't need to iterate the children, just use find 
# and you need to use attrs { key: value }, not just 'time_rtq_ticker' 
soup.find('span', attrs={'class':'time_rtq_ticker'}).text 
u'17,554.47' 
+0

正是我在找什麼。非常感謝! – 2014-11-06 23:12:47

+0

不是問題:) – Anzel 2014-11-06 23:13:21