通过urllib / urllib2发送POST请求?

时间:2011-08-23 10:08:22

标签: python post request urllib2 urllib

在你说什么之前,我环顾四周,解决方案没有用。我需要在Python中对登录脚本发出post请求。该网址看起来像http://example.com/index.php?act=login,然后通过POST接受usernamepassword。任何人都可以帮我这个吗?

我试过了:

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

1 个答案:

答案 0 :(得分:1)

您可能需要查看HTML源代码以找出登录表单操作URL的内容。有时它与页面URL本身相同,但它可能不同。但由于您没有显示实际的网址,我们无法帮助您。

<form>元素可能类似于:

<form method="POST" action="/do_login">

在这种情况下,您可以在POST网址中使用/do_login