2013-05-14 50 views
1

我一直在嘗試了一段時間,現在登錄到我的谷歌帳戶,並從中下載文件,而無需使用任何外部庫。 我特別談論Google財經(https://www.google.com/finance)。 我想要做的就是登錄,然後下載我的投資組合(在您登錄並轉到投資組合選項卡後,有一個鏈接:下載到電子表格)。 但我無法讓它工作。登錄到谷歌使用Python

我在這裏看到了幾個關於類似問題的帖子,但他們都沒有爲我工作。

這是我現在的代碼:

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() 

我在做什麼錯?

非常感謝!

+0

你有什麼錯誤? – Colleen

+0

該文件正在下載,但它是空的。就像您嘗試使用指定的鏈接下載您的投資組合一樣,而無需登錄。 – user1476876

+0

您需要通過POSTing登錄到「https:// accounts.google.com/ServiceLoginAuth」。您要訪問的網址只是登錄頁面,您需要實際模擬登錄表單提交。使用FireBug或Google開發工具網絡面板獲得更多關於如何進行登錄呼叫的細節。 –

回答

0

筆者的script你提到的自更新上述腳本(S)。這些腳本是專門爲gVoice設計的,但可以用gFinance作爲您的需求的例子,我確信。

新的腳本在GitHub發現。