2014-09-11 147 views

回答

2

執行此類任務時需要考慮兩個方面。首先,如果您控制了要與之通信的網站,並且第二,如果該網站具有API。您需要根據這些使用不同的庫。

如果您想要訪問的網站有一個API,您可以直接從您的程序與它通信,即調用方法並以'機器友好'格式獲得結果,如Json,XML等等。如果網站沒有API,則需要模仿用戶交互和解析HTML,對於這些情況,測試工具通常會很好地執行此操作。

例如,你可以使用從Django的測試工具the test client,如果你要訪問的網站是本地Django的一個:

>>> from django.test.client import Client 
>>> c = Client() 
>>> response = c.post('/login/', {'username': 'john', 'password': 'smith'}) 
>>> response.status_code 
200 
>>> response = c.get('/customer/details/') 
>>> response.content 
'<!DOCTYPE html...' 

一旦你自己打電話給你不會使用jQuery但蟒蛇。你通常會在response.content裏面找到答案,你可能需要解析它,假設你得到了一個html。

如果您要訪問的網站是一個第三方的,我會用requests library,你需要寫的東西是這樣的:

>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass')) 
>>> r.status_code 
200 
>>> r.headers['content-type'] 
'application/json; charset=utf8' 
>>> r.encoding 
'utf-8' 
>>> r.text 
u'{"type":"User"...' 
>>> r.json() 
{u'private_gists': 419, u'total_private_repos': 77, ...} 

這將是簡單得多,如果網站想你訪問有一個API,您可以通過REST調用來訪問它,這是上面的請求庫示例。根據你想要訪問的網站,你可能已經有了一個Python庫,它通常是這些API調用的一個包裝。

+0

不,我想登錄到gmail.com !!(不是我自己的網站) 我認爲,因爲它在文檔中說: _allowing您測試**您的意見**並以編程方式與您的Django供電應用程序進行交互和它不適用於登錄到其他網站! – 2014-09-11 11:55:36

+0

答案仍然有效,因爲它是一般性答案。相同的準則適用於(幾乎)任何網站。特別是對於Gmail,我會使用[Gmail Api](https://developers.google.com/gmail/api/),它特別支持[Python](https://developers.google.com/api-client -library /蟒/)。尋找網站的API是我給出的第二個建議。 – RobertoAllende 2014-09-11 20:23:51

+0

不,測試客戶端是** Your Own **網站,不是沒有任何API的另一個網站! – 2014-09-11 20:28:04

2

經過大量的搜索,終於找到2solutions:
1)使用這個驚人的流行Django的包
Django Requests Packagedocumantation說,我可以做到這一點:

import requests 

r = requests.get('https://api.github.com', auth=('user', 'pass')) 

print r.status_code 
print r.headers['content-type'] 

# ------ 
# 200 
# 'application/json' 

2 )第二種解決方案是使用Python URL Libray

import urllib2 

gh_url = 'https://api.github.com' 

req = urllib2.Request(gh_url) 

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() 
password_manager.add_password(None, gh_url, 'user', 'pass') 

auth_manager = urllib2.HTTPBasicAuthHandler(password_manager) 
opener = urllib2.build_opener(auth_manager) 

urllib2.install_opener(opener) 

handler = urllib2.urlopen(req) 

print handler.getcode() 
print handler.headers.getheader('content-type') 

# ------ 
# 200 
# 'application/json'