【发布时间】:2015-11-06 12:35:47
【问题描述】:
我对 python 和一般编程很陌生。我目前正在编写一个脚本来从谷歌金融中抓取股票报价。这是我的代码:
import urllib.request as ur
import re
def getquote(symbol):
base_url = 'http://finance.google.com/finance?q='
content = ur.urlopen(base_url + symbol).read()
m = re.search(b'id="ref_(.*?)">(.*?)<', content)
if m:
quote = m.group(2)
else:
quote = 'no quote available for: ' + symbol
return quote
返回:
b'655.65'
(655.65 是谷歌股票的当前价格,是我传入的代码)
我的问题是:有没有办法让我清除退货,这样我就可以得到不带 b 或报价单的价格?理想情况下,我希望将其作为浮点数返回,但如果需要,我可以将其作为字符串返回,并在以后需要时将其转换为浮点数。
我参考了这些其他帖子:
How to create a stock quote fetching app in python
How to convert between bytes and strings in Python 3?
Convert bytes to a Python string
也许我在其中一个中遗漏了一些东西,但我相信我已经尝试了我能找到的所有东西,但它仍然以上面显示的格式返回。
已解决 我遇到的问题不是显示没有引号的字符串,而是我将一个值设置为字节文字,需要先转换为字符串文字,然后再转换为浮点数。我试过这个,但我在 if 语句之外尝试了这个(noob move)。解决方案如 v1k45 建议的那样: 在 if 语句中添加一行 报价=浮动(quote.decode('utf-8')) 对其进行解码并转换为浮点数。
感谢您的帮助!
【问题讨论】:
标签: python regex screen-scraping finance stock