2010-12-01 185 views
1

我知道類似的問題已經被問到,我已經閱讀過。我還閱讀了我能找到的大多數其他相關文章。我已經嘗試httplib2,標題修改,以及任何我可以找到或想到的,但我無法獲得此登錄腳本工作。Python登錄腳本

import cookielib 
import urllib 
import urllib2 

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
resp = opener.open('http://www.biocidecity.com') 

theurl = 'http://www.biocidecity.com/index.php' 
body={'username':'someusername','password':'somepassword', 'login' : '1'} 
txdata = urllib.urlencode(body) txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} 


try: 
    req = urllib2.Request(theurl, txdata, txheaders) 
    handle = opener.open(req) 
    HTMLSource = handle.read() 
    f = file('test.html', 'w') 
    f.write(HTMLSource) 
    f.close() 

except IOError, e: 
    print 'We failed to open "%s".' % theurl 
    if hasattr(e, 'code'): 
     print 'We failed with error code - %s.' % e.code 
    elif hasattr(e, 'reason'): 
     print "The error object has the following 'reason' attribute :", e.reason 
     print "This usually means the server doesn't exist, is down, or we don't have an internet connection." 
     sys.exit() 

else: 
    print 'Here are the headers of the page :' 
    print handle.info() 

首先,這不是我的腳本,但我修改了一些。其次,我認爲這與cookie的處理方式有關,但我無法弄清楚。我也替換了用戶名密碼組合。

+1

「我不能讓這個登錄腳本的工作」。你也許應該定義**正在做什麼以及爲什麼你不喜歡那樣做。它是否有語法錯誤?它是否從Web服務器返回401錯誤?你看到了什麼結果? – 2010-12-01 17:53:42

回答

2

我想它再次服務的期限,但你應該嘗試

import cookielib 
import urllib 
import urllib2 

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
resp = opener.open('http://www.biocidecity.com') 

theurl = 'http://www.biocidecity.com/index.php' 
body={'username':'someusername','password':'somepassword', 'login' : '1'} 
txdata = urllib.urlencode(body) txheaders = {'Referer': 'http://www.biocidecity.com/index.php'} 


try: 
    req = urllib2.Request(theurl, txdata, txheaders) 
    handle = opener.open(req) 
    HTMLSource = handle.read() 
    f = file('test.html', 'w') 
    f.write(HTMLSource) 
    f.close() 

except IOError, e: 
    print 'We failed to open "%s".' % theurl 
    if hasattr(e, 'code'): 
     print 'We failed with error code - %s.' % e.code 
    elif hasattr(e, 'reason'): 
     print "The error object has the following 'reason' attribute :", e.reason 
     print "This usually means the server doesn't exist, is down, or we don't have an internet connection." 
     sys.exit() 

else: 
    print 'Here are the headers of the page :' 
    print handle.info()