0

このコードは、reddit の stackoverflow のどこかにありました。hackthissite.org 用に変更してみました:

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 のログイン フォームです。

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

サーバーからの応答は次のとおりです。

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

どうすればサイトにログインできますか? この場合、サーバーの応答はどういう意味ですか? (AddInfoUrl ?)

4

2 に答える 2

1
resp = urllib2.urlopen(req)

urlopen基本的に、応答を読み取ることができるハンドルである「ファイルのような」オブジェクトを返します。サーバーの応答テキストだけに関心がある場合はread、応答オブジェクトを呼び出すだけです。

print resp.read()

さらにinfo、応答ヘッダーに関する情報を提供するなどの追加のメソッドもいくつかあります。

于 2013-07-30T00:20:06.163 に答える