-1

我正在尝试使用 python3 从 Google Finance 中抓取一些股票价格和变化,但我无法确定页面或我的正则表达式是否有问题。我认为 svg 图形或整个页面的许多脚本标签都使正则表达式解析器无法正确分析代码。

我已经在许多在线正则表达式构建器/测试器上测试了这个正则表达式,它看起来还可以。无论如何,就像为 HTML 设计的正则表达式一样好。

我正在测试的 Google Finance 页面是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 有一些奇怪的地方。

这是我要实现的最重要的 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>

我想知道你们中是否有人在这个页面上遇到过类似的问题和/或可以弄清楚我的代码是否有任何问题。提前致谢!

4

2 回答 2

0

我设法在最初发布的链接上使用 BeautifulSoup 让它工作。

这是我最终使用的代码:

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中的表格,而不是我发布的表格。我的问题中描述的两种方法都不适用于此页面。

于 2014-10-17T14:36:30.460 回答
0

您可以尝试其他更易于解析的 URL,例如:http ://www.google.com/finance/info?q=AAPL

问题是谷歌曾表示,在公共消费应用程序中使用此 API 违反了他们的服务条款。也许谷歌会允许你使用另一种选择?

于 2014-10-16T21:34:37.277 回答