问题
Before you say anything, I've looked around SO and the solutions didn't work. I need to make a post request to a login script in Python. The URL looks like http://example.com/index.php?act=login, then it accepts username
and password
via POST. Could anyone help me with this?
I've tried:
import urllib, urllib2, cookielib
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders.append(('User-agent', 'Mozilla/4.0'))
opener.addheaders.append( ('Referer', 'http://www.hellboundhackers.org/index.php') )
login_data = urllib.urlencode({'username' : '[redacted]',
'password' : '[redacted]'
})
resp = opener.open('http://[redacted].org/index.php?act=login', login_data)
print resp.read()
resp.close()
and a little bit modified:
import urllib, urllib2, cookielib
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders.append(('User-agent', 'Mozilla/4.0'))
opener.addheaders.append( ('Referer', 'http://www.hellboundhackers.org/index.php') )
login_data = urllib.urlencode({'act' : 'login',
'username' : '[redacted]',
'password' : '[redacted]'
})
resp = opener.open('http://[redacted].org/index.php', login_data)
print resp.read()
resp.close()
回答1:
You will probably need to look at the HTML source to find out what the login form action URL is. Sometimes it is the same as the page URL itself, but it's probably different. But since you haven't shown actual URLs, we can't help you there.
The <form>
element might look something like:
<form method="POST" action="/do_login">
In that case, you would use /do_login
in your POST url.
来源:https://stackoverflow.com/questions/7159376/post-request-via-urllib-urllib2