通过 urllib/urllib2 POST 请求?
在你说什么之前,我已经环顾四周,但解决方案不起作用。我需要用 Python 向登录脚本发出发布请求。该 URL 类似于 http://example.com/index.php?act=login ,然后它通过 POST 接受用户名
和密码
。有人能帮我解决这个问题吗?
我已经尝试过:
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()
并进行了一些修改:
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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要查看 HTML 源代码来找出登录表单操作 URL 是什么。有时它与页面 URL 本身相同,但也可能不同。但由于您没有显示实际的网址,我们无法为您提供帮助。
在这种情况下,您将在 POST url 中使用
/do_login
。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:In that case, you would use
/do_login
in your POST url.