2016-02-13 52 views
1

我有一個Python 2.6腳本,用於下載Web服務器中的文件。我想這個這個腳本(在抓取文件之前authenrication)通過用戶名和密碼,我將它們作爲URL的一部分如下:從https下載帶有身份驗證的文件

import urllib2 
response = urllib2.urlopen("http://'user1':'password'@server_name/file") 

但是,我得到的語法錯誤在這種情況下。這是否是正確的方法?我對Python和一般編碼都很陌生。 有人可以幫我嗎? 謝謝!

+0

服務器如何期待他們?轉到網址並在開發工具中打開網絡選項卡登錄並查看請求的樣子 – IanAuld

+0

請參閱https://docs.python.org/2/howto/urllib2.html#id6 – Selcuk

回答

3

我想你正試圖通過基本認證。在這種情況下,你可以這樣處理:

import urllib2 

username = 'user1' 
password = '123456' 

#This should be the base url you wanted to access. 
baseurl = 'http://server_name.com' 

#Create a password manager 
manager = urllib2.HTTPPasswordMgrWithDefaultRealm() 
manager.add_password(None, baseurl, username, password) 

#Create an authentication handler using the password manager 
auth = urllib2.HTTPBasicAuthHandler(manager) 

#Create an opener that will replace the default urlopen method on further calls 
opener = urllib2.build_opener(auth) 
urllib2.install_opener(opener) 

#Here you should access the full url you wanted to open 
response = urllib2.urlopen(baseurl + "/file") 
+0

如何保存下載數據在一個特定的文件? – Estefy

4

如果你可以使用requests庫,這是非常輕鬆。如果可能,我強烈建議使用它:

import requests 

url = 'http://somewebsite.org' 
user, password = 'bob', 'I love cats' 
resp = requests.get(url, auth=(user, password)) 
+0

'request.get'在最後一行不適用於我。我想它應該更正爲'requests.get'與's' – deppfx

0

使用請求庫並將憑據放入.netrc文件中。

該庫將從那裏加載它們,您將能夠將代碼提交給您選擇的SCM,而不會有任何安全隱患。