Python 如何使用urllib2将数据发布到身份验证服务器

Python 如何使用urllib2将数据发布到身份验证服务器,python,post,urllib2,Python,Post,Urllib2,我有一些python代码,它使用requests模块访问特定网站上的页面。我正在尝试使用标准的libraby,特别是urllib2来重做这个 以下是使用请求的工作代码: 这将返回以下错误 urllib2.HTTPError:HTTP错误302:HTTP服务器返回一个重定向错误,该错误将导致无限循环。 最后一条30倍的错误消息是: 建立 这是因为我发布的url与我想要阅读的url不同吗?有人能为这个问题提供解决方案吗 谢谢 John如果您有一个更简单、有效的请求解决方案,为什么要尝试使用urlli

我有一些python代码,它使用requests模块访问特定网站上的页面。我正在尝试使用标准的libraby,特别是urllib2来重做这个

以下是使用请求的工作代码:

这将返回以下错误

urllib2.HTTPError:HTTP错误302:HTTP服务器返回一个重定向错误,该错误将导致无限循环。 最后一条30倍的错误消息是: 建立 这是因为我发布的url与我想要阅读的url不同吗?有人能为这个问题提供解决方案吗

谢谢
John

如果您有一个更简单、有效的请求解决方案,为什么要尝试使用urllib2执行此操作?@Blender-我想在只有标准库可用的环境中运行它。请求不在标准库中
import requests

#Now create a session
s = requests.session()

#look at login screen at http://supercoach.heraldsun.com.au/
#looking closely at what gets 'POSTed' when you submit the form
#it is sending the following params:

data = {
    'username'      :'test_account@scscorecollector.info',
    'password'      :'magicword',
    'remember_me'   :'on',
    'channel'       :'pc',
    'site'          :'HeraldSun',
    'cancelUrl'     :'http://supercoach.heraldsun.com.au/?identity-login-error=1',
    'relayState'    :'http://supercoach.heraldsun.com.au/?login=1',
    'location'      :'http://saml.cam.idmndm.com',
}




#This data gets POSTed to https://idp.news.com.au/idp/Authn/rest, but we want to read  a differnet url
url_post = 'https://idp.news.com.au/idp/Authn/rest/'
url_read ='http://supercoach.heraldsun.com.au/team/other_teams?tid=11088'


r = s.post(url_post, data=data)

#Now that you are logged in, you can call the URL we want to read:

r = s.get(url_read)
print r

#<Response [200]>
import urllib2
import urllib
import cookielib

data = {'username'      :'test_account@scscorecollector.info',
    'password'      :'magicword',
    'remember_me'   :'on',
    'channel'       :'pc',
    'site'          :'HeraldSun',
    'cancelUrl'     :'http://supercoach.heraldsun.com.au/?identity-login-error=1',
    'relayState'    :'http://supercoach.heraldsun.com.au/?login=1',
    'location'      :'http://saml.cam.idmndm.com'}

#some data
url_post = 'https://idp.news.com.au/idp/Authn/rest'
url_read ='http://supercoach.heraldsun.com.au/team/other_teams?tid=11088'
user_agent = 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0'

headers = { 'User-Agent' : user_agent }
data_encode = urllib.urlencode(data)

# setup cookie handler and create opener
cookie_jar = cookielib.LWPCookieJar()
cookie = urllib2.HTTPCookieProcessor(cookie_jar)
opener = urllib2.build_opener(cookie)

# post to 
req = urllib2.Request(url_post, data_encode, headers)
req.get_method = lambda: 'POST'
response = opener.open(req)