使用Python登录谷歌

时间:2013-05-14 21:14:12

标签: python python-2.7 google-oauth google-finance

我已经尝试了一段时间登录我的Google帐户并从中下载文件而不使用任何外部库。 我特别谈到Google财经(https://www.google.com/finance)。 我想要做的就是登录,然后下载我的投资组合(在您登录并转到投资组合选项卡后,有一个链接说:下载到电子表格)。 但我无法让它发挥作用。

我在这里看到过几个关于类似问题的帖子,但没有一个对我有用。

这是我现在的代码:

import urllib, urllib2, cookielib

#Gets the current directory
output_path = os.getcwd()

def make_url(ticker_symbol):
    return base_url + ticker_symbol

def make_filename(ticker_symbol):
    return output_path + "\\" + ticker_symbol + ".csv"

# Login page for Google Finance
login_url = "https://accounts.google.com/ServiceLogin?service=finance&passive=1209600&continue=https://www.google.com/finance&followup=https://www.google.com/finance"

# Google Finance portfolio Download url (works after you signed in)
download_url = "https://www.google.com/finance/portfolio?pid=1&output=csv&action=viewt&ei=ypZyUZi_EqGAwAP5Vg"

username = 'my_username'
password = 'my_password'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open(login_url, login_data)

# Download the file
try:
    urllib.urlretrieve(download_url, make_filename("My_portfolio"))
except urllib.ContentTooShortError as e:
    outfile = open(make_filename("My_portfolio"), "w")
    outfile.write(e.content)
    outfile.close()

我做错了什么?

非常感谢!!

1 个答案:

答案 0 :(得分:0)

你提到的script的作者已经更新了上述脚本。这些脚本专为gVoice设计,但我可以用gFinance作为您的需求的例子。

新脚本位于GitHub