2013-05-02 18 views
1

我打算使用Requests和PyQuery在Python中編寫網站抓取工具。建立會話與網頁應用程序抓取

但是,我要定位的網站要求我登錄到我的帳戶。使用請求,是否有可能與服務器建立會話(使用我的網站憑據),並使用此會話來爬網我只有登錄時才能訪問的網站?

我希望這個問題很清楚,謝謝。

+1

當然可以。 'request'本身有很多方法可以做到這一點,如果不支持,你也可以編寫自己的認證方法。請參閱http://docs.python-requests.org/en/latest/user/authentication/ – michaelmeyer 2013-05-02 15:13:48

+1

絕對有可能,但只是爲網站準備好趕走你,並有可能刪除你的帳戶,如果他們趕上你。根據服務條款和您正在翻錄的信息的價值,網站可能不會太高興。該網站可能會記錄用戶活動,並且很容易找到抓取工具(儘管很少有網站實際正在尋找此工具令人驚訝) – 2013-05-02 15:37:32

回答

2

是的,這是可能的。

我不知道PyQuery,但我已經使用urllib2登錄到網站的抓取工具。 您只需使用cookiejar來處理cookie並使用請求發送登錄表單。

如果你問一些更具體的問題,我會盡量更加明確。

LE: urllib2不是一團糟。在我看來,這是最好的圖書館。

這裏有一小段代碼片段,將登錄到網站(之後,你可以只解析該網站正常):

import urllib 
import urllib2 
import cookielib 

"""Adding cookie support""" 
cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
urllib2.install_opener(opener) 

"""Next we will log in to the site. The actual url will be different and also the data. 
You should check the log in form to see what parameters it takes and what values. 

""" 
data = {'username' : 'foo', 
     'password' : 'bar' 
     } 
data = urllib.urlencode(data) 
urllib2.urlopen('http://www.siteyouwanttoparse.com/login', data) #this should log us in 

"""Now you can parse the site""" 
html = urllib2.urlopen('http://www.siteyoutwanttoparse.com').read() 
print html 
+1

感謝此信息。理想情況下,我正在尋找的是一個Python請求片段來執行相關的Cookie /會話處理。我想避免使用urllib2,因爲它是一種混亂.. – 2013-05-02 15:02:21

+0

@ B.VB。我已更新我的帖子 – 2013-05-02 16:29:35