2013-07-29 9 views
0

이 코드는 어딘가에 reddit에 대한 stackoverflow에 있습니다. 내가 hackthissite.org에 대한 수정을 시도 :Python : 웹 사이트에 로그인

<form id="loginform" method="post" action="/user/login"> 
<div id="innerlogin"> 
     <script type="text/javascript">var userclicked=0; var passclicked=0;</script> 
     <p><input type="text" name="username" class="login" value="" onclick="if(userclicked==0){this.value='';userclicked=1;};" title="Username" /></p> 
     <p><input type="password" name="password" class="login" value="" onclick="if(passclicked==0){this.value='';passclicked=1;};" title="Password" /></p> 
     <p><input type="submit" value="Login" name="btn_submit" class="submit-button" /></p> 
</div> 
</form> 

내가 얻는 응답 : 나는 페이로드 권리를 가지고 말할 수있는 지금까지

import urllib2 
import urllib 
import cookielib 

# Store the cookies and create an opener to hold them 
cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 

# Add our headers 
opener.addheaders = [('User-agent', 'Tester')] 

# Install the opener, changes the global opener to the one we just made 
urllib2.install_opener(opener) 

# URL for authentification 
auth_url = 'https://www.hackthissite.org/user/login' 

# Parameters to send 
payload = { 
    'username': 'myUser', 
    'password': 'myPass', 
    'btn_submit': 'Login' 
} 

# Encode payload 
data = urllib.urlencode(payload) 

# Build request object (supplying 'data' makes it a POST) 
req = urllib2.Request(auth_url, data) 

# Make request and store in resp 
resp = urllib2.urlopen(req) 

print resp 

을,이 hackthissite.org에 로그인 폼이다 서버에서 :

<addinfourl at 36515712 whose fp = <socket._fileobject object at 0x022D3DB0>> 

어떻게 사이트에 로그인 할 수 있습니까? 이 경우 서버 응답이 의미하는 것은 무엇입니까? (AddInfoUrl?)

답변

6

mechanize을 살펴보고 대신 사용하는 것이 좋습니다. 그것은 이런 종류의 일을 거의 사소한 것으로 만듭니다. 이 라인을 설명하기 위해 :

from mechanize import Browser 

br = Browser() 
br.open("https://www.hackthissite.org/user/login") 

br.select_form(predicate=lambda f: f.attrs.get('action') == '/user/login') 
br["username"] = "myUser" 
br["password"] = "myPass" 
response = br.submit() 

print response.read() 

UPDATE : 예를 들어, 여기에 당신은 당신이 언급 한 사이트 인터페이스 줄 방법 ​​

br.select_form(predicate=lambda f: f.attrs.get('action') == '/user/login') 

select_form이 중 하나 nr 인수, 또는 name 인수, 또는 predicate 소요 논의. br.select_form(nr=1)을 수행하면 페이지의 두 번째 양식이 선택됩니다. br.select_form(name="foobar")을 수행하면 페이지에서 "foobar"라는 첫 번째 양식이 선택됩니다. 또는 HTMLForm 객체를 취하는 함수를 제공하고 그 객체를 선택해야하는지 여부를 반환 할 수 있습니다.

위의 경우 양식의 "action" 특성이 "/user/login" 인 경우 true를 반환하는 함수를 제공합니다. 문서에서 양식의 이름이나 위치를 아는 것이 더 쉽습니다.

+0

감사합니다. 내가 살펴볼 것입니다! 술어 = lambda f : f.attrs.get ('조치') == '/ user/login' 조치가있는 br에서 양식을 선택한다는 것을 알고 있습니다 =/user/login "하지만 술어 = lambda f는 무엇을 의미합니까? – Juicy

+0

확실한 것, 업데이트 확인 – Claudiu

+0

남자 감사합니다! – Juicy

1
resp = urllib2.urlopen(req) 

urlopen은 본질적으로 당신의 응답을 읽을 수있는 핸들입니다 "파일 같은"개체를 반환합니다. 서버의 응답 텍스트에만 관심이 있다면, 당신은 단지 응답 오브젝트에 read를 호출 할 수 있습니다 또한

print resp.read() 

을, 당신 또한 당신에게 응답 헤더에 대한 정보를 제공 info 같은 몇 가지 추가 방법.