urllib2 HTTPPasswordMgr not working - Credentials not sent error

淺唱寂寞╮ 提交于 2019-12-01 23:34:35
paragbaxi

From Python urllib2 Basic Auth Problem

The problem [is] that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the ... servers don't do "totally standard authentication" then the libraries won't work.

This particular API does not respond with a 401 Unauthorized on the first attempt, it responds with an XML response containing the message that credentials were not sent with a 200 OK response code.

Try setting the user agent, maybe thats whats interfering. urllib2 identifies itself as Python-urllib/x.y (where x and y are the major and minor version numbers of the Python release, e.g. Python-urllib/2.5) this might be whats causing the site to block your request. Take a look at their robots.txt.. here is an example on setting the user agent so as you're script is identified as a browser:

import urllib
import urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!