2017-05-14 40 views
2

我一直在撞牆,試圖從新聞來源「SNL Finance」中檢索內容。我有有效的證書,所以理論上我應該能夠以編程方式訪問他們的新聞內容。Python請求訪問OAUTH網站內容 - SNL Finance

總之,我已經試過執行下面的腳本,但沒有成功:

s = requests.Session() 

client_id = "..." 
client_secret = "..." 
token_url = "https://www.snl.com/SNL.Services.Security.Service/oauth/token" 
protected_url = "https://www.snl.com/web/client?auth=inherit#news/article?id=40666532&KeyProductLinkType=14" 

request_data = { 
    "client_id": client_id, 
    "client_secret": client_secret, 
    "scope": "https://www.snl.com", 
    "grant_type": "refresh_token", 
    "refresh_token": refresh_token 
} 

token_response = s.post(token_url, data=request_data) 
### token response is in jwt format, including token_type, expires_in, scope, etc. ### 
token = json.loads(token_response.text)["access_token"].split('>')[1].split('<')[0] 
request_data["token"] = token 

article = s.post(protected_url, headers=request_data) 

可悲的是,這種失敗。我最終得到了200個響應,但它似乎只是登錄頁面(實際上並不完全確定我在看什麼)。

欲瞭解更多的背景,我已經包括瀏覽器的信息,因爲它填充整個認證過程:

  1. 試圖訪問受保護的URL,重定向到URL下(略SNL基地):

    /web/client?auth=inherit&contextType=external&username=string&enablePersistentLogin=true&OverrideRetryLimit=0&SwitchGetToPostLimit=50000&contextValue=%2Foam&password=secure_string&challenge_url=https%3A%2F%2Fwww.snl.com%2Fweb%2Fclient%3Fauth%3Dinherit&request_id=-6149669210818920852&authn_try_count=0&locale=en_US&resource_url=https%253A%252F%252Fwww.snl.com%252FInteractiveX%252FDefault.aspx%253Ftarget%253Dnews%25252Farticle%25253Fid%25253D40666532%252526KeyProductLinkType%25253D14%2526SNL3%253D1 
    

請求標頭顯示here

  1. 輸入登錄名/密碼後,會檢索令牌並加載受保護的頁面。

要求cookies如圖所示here

此外,我對以上link (second link)中的SNL_OAUTH_TOKEN的標記值與我從腳本收到的jwt標記響應中顯示的標記值有什麼不同有點困惑。

任何指導在這裏將非常感激。我也很樂意發送任何證明有用的非個人信息。

謝謝!

回答

0

我最終弄清楚了這一點。我低估了Python的請求庫。

這似乎是因爲這很容易:

# prep token request data 
request_data = { 
    "client_id": client_id, 
    "client_secret": client_secret, 
    "scope": "https://www.snl.com", 
    "grant_type": "refresh_token", 
    "refresh_token": new_refresh_token 
} 

# post to token url with token credentials 
# the request object stores the token response cookies 
r1 = requests.post(token_url, data=request_data) 

# post to protected url by setting cookies arg as cookies from previous response 
r2 = requests.post(protected_url, cookies=r1.cookies) 
+0

有很多OAuth客戶端庫和擴展能力的要求是https://github.com/requests/requests-oauthlib,你可以將一個想結賬。 – Smit