POST request via urllib/urllib2?

為{幸葍}努か 提交于 2019-12-12 19:11:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!