2014-10-16 66 views
-1

我試圖從Google Finance使用python3刮取一些股票價格和變體,但我無法弄清楚如果頁面或我的正則表達式出現問題。我在想,整個頁面中的svg圖形或許多腳本標記都會使正則表達式解析器無法正確分析代碼。無法解析Google財經html

我在許多在線正則表達式構建器/測試器上測試了這個正則表達式,它看起來沒問題。無論如何,正如專爲HTML設計的正則表達式一樣。

的谷歌財經頁面我在測試這一點是https://www.google.com/finance?q=NYSE%3AAAPL 我的Python代碼如下

import urllib.request 
import re 
page = urllib.request.urlopen('https://www.google.com/finance?q=NYSE%3AAAPL') 
text = page.read().decode('utf-8') 
m = re.search("id=\"price-panel.*>(\d*\d*\d\.\d\d)</span>.*\((-*\d\.\d\d%)\)", text, re.S) 
print(m.groups()) 

這將提取的股票價格及其變動百分比。 我一直在使用python2 + BeautifulSoup也試過,像這樣

soup.find(id='price-panel') 

但即使是這樣一個簡單的查詢返回空。這尤其是爲什麼我認爲這有點奇怪的HTML。

而這裏的是我的目標

<div id="price-panel" class="id-price-panel goog-inline-block"> 
<div> 
<span class="pr"> 
<span class="unchanged" id="ref_22144_l"><span class="unchanged">96.41</span><span></span></span> 
</span> 
<div class="id-price-change nwp goog-inline-block"> 
<span class="ch bld"><span class="down" id="ref_22144_c">-1.13</span> 
<span class="down" id="ref_22144_cp">(-1.16%)</span> 
</span> 
</div> 
</div> 
<div> 
<span class="nwp"> 
Real-time: 
&nbsp; 
<span class="unchanged" id="ref_22144_ltt">3:42PM EDT</span> 
</span> 
<div class="mdata-dis"> 
<span class="dis-large"><nobr>NASDAQ 
real-time data - 
<a href="//www.google.com/help/stock_disclaimer.html#realtime" class="dis-large">Disclaimer</a> 
</nobr></span> 
<div>Currency in USD</div> 
</div> 
</div> 
</div> 

我想知道如果你們任何人都遇到類似的問題,此頁面和/或可以計算出,如果有什麼事,HTML中最重要的位我的代碼錯了。提前致謝!

+1

僅供參考,https://www.quandl.com/help/api-for-stock-data我不知道Google Finance需要什麼,但您可以從此處獲得。 – user2023861 2014-10-16 20:50:23

+0

@ user2023861謝謝,我會檢查出來的。我曾經搜索過其他來源的數據,但沒有發現我擁有的所有股票。我試圖從除紐約證券交易所以外的交易所獲得股票。 – Slpk 2014-10-17 14:01:40

回答

0

你可以嘗試不同的URL,這將是更容易分析,如:http://www.google.com/finance/info?q=AAPL

美中不足的是,谷歌曾表示,在大衆消費應用程序中使用這個API是對他們的服務條款。也許有一種方法可以讓Google使用?

+0

酷,它肯定比解析HTML好多了。我認爲有用的另一個隱藏來源是https://www.google.com/finance/getprices?q=AAPL&i=120&p=5d&f=c&df=cpct&auto=1 – Slpk 2014-10-17 14:04:30

0

我設法使用BeautifulSoup,在最初發布的鏈接上工作。

這是我finaly使用的代碼位:

response = urllib2.urlopen('https://www.google.com/finance?q=NYSE%3AAAPL') 
html = response.read() 
soup = BeautifulSoup(html, "lxml") 
aaplPrice = soup.find(id='price-panel').div.span.span.text 
aaplVar = soup.find(id='price-panel').div.div.span.find_all('span')[1].string.split('(')[1].split(')')[0] 
aapl = aaplPrice + ' ' + aaplVar 

我無法得到它與BeautifulSoup工作之前,因爲我其實是試圖解析表中https://www.google.com/finance?q=NYSE%3AAAPL%3BNYSE%3AGOOG這個頁面,而不是一個我張貼。 我的問題描述的兩種方法都不適用於此頁面。