2010-12-01 2 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() 

처음에는 내 스크립트가 아니지만 일부 수정했습니다. 둘째로 쿠키가 처리되는 방식과 관련이 있다고 생각하지만 이해할 수는 없습니다. 나는 또한 사용자 이름 암호 조합을 대체했습니다.

+1

"나는 작업이 로그인 스크립트를 얻을 수 없다"시도해야합니다. 당신은 ** 그것이 ** 무엇을하고, 왜 당신이 그것을 좋아하지 않는지를 정의해야합니다. 구문 오류가 있습니까? 웹 서버에서 401 오류를 반환합니까? 그 결과로 무엇을 보았습니까? –

+0

실수로 Wireshark에서 상호 작용을 볼 때 서버는 내가 게시 한 로그인 페이지 (즉, 리디렉션되지 않은 페이지)를 반환합니다. 그 외에는 오류가없고 아무것도 없습니다. 내가 찾을 수있는 유일한 차이점은 Chrome에서 302 응답 패킷에 http 헤더의 쿠키 정보가 포함되어있는 양식을 제출할 때 스크립트를 사용할 때가 아니라는 것입니다 ... 음 ... 어쩌면 내 질문을 다시 말해야합니다. – John

+0

"아마도 내 질문을 다시 말해야합니다." 전혀. ** 당신이 겪고있는 문제에 대해 명확히하기 위해 ** 업데이트 **하십시오. –

답변

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()