通过urllib/urllib2发出POST请求? [英] POST request via urllib/urllib2?

查看:376
本文介绍了通过urllib/urllib2发出POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在您发表任何言论之前,我已经环顾四周,并且解决方案无效.我需要向Python中的登录脚本发出发布请求.该网址看起来像 http://example.com/index.php?act=login ,然后它通过POST接受usernamepassword.有人可以帮我吗?

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?

我尝试过:

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

推荐答案

您可能需要查看HTML源代码,以了解什么是登录表单操作URL.有时它与页面URL本身相同,但可能有所不同.但是,由于您没有显示实际的网址,因此我们无法为您提供帮助.

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.

<form>元素可能类似于:

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

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

In that case, you would use /do_login in your POST url.

这篇关于通过urllib/urllib2发出POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆