为什么我无法在post方法中使用python登录此站点

时间:2011-03-28 01:25:23

标签: python login urllib2 cookielib

这是我使用python登录网站的代码:

import urllib2, cookielib
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.urlopen('http://192.168.1.200/order/index.php?op=Login&ac=login&userName=%E8%B5%B5%E6%B1%9F%E6%98%8E&userPwd=123').read()

print content

它显示:

{"title":"login error","body":"username or password error","data":{"status":1}}

但用户名和密码是对的,我可以使用firefox登录此站点,

所以我该怎么做,

感谢

2 个答案:

答案 0 :(得分:3)

您正在发出GET请求。要发出POST请求,请使用:

content = urllib2.urlopen(
    'http://192.168.1.200/order/index.php",
    'op=Login&ac=login&userName=%E8%B5%B5%E6%B1%9F%E6%98%8E&userPwd=123').read()

如果向其传递数据(第二个参数),urlopen方法将发送POST请求。

答案 1 :(得分:0)

尝试使用密码管理器:

来自here

# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)