从python urllib2.urlopen调用中不时收到401错误

1 投票
1 回答
1327 浏览
提问于 2025-04-17 05:25

我有一个用Python写的脚本,它通过urllib2来访问一系列网址。这个网址是用http协议的,但需要登录认证。我现在想让这个脚本运行超过100次调用。每次运行脚本时,有些调用会失败,显示401错误代码,而有些则成功。所有的调用都是针对同一个网址,使用的是相同的用户名和密码。(每次运行脚本时,失败的调用并不相同,有时第一次调用失败,有时又成功。)

你觉得为什么会出现不一致的401错误呢?

屏幕上打印的错误信息是……

下面是负责进行网址调用的方法:

def simpleExecuteRequest(minX, minY, maxX, maxY, type) :
    url = 'http://myhost.com/geowebcache/rest/seed/mylayer.xml'

    msgTemplate = """<?xml version=\"1.0\" encoding=\"UTF-8\"?>
    <seedRequest>
    <name>mylayer</name>
    <bounds>
    <coords>
    <double>%s</double>
    <double>%s</double>
    <double>%s</double>
    <double>%s</double>
    </coords>
    </bounds>
    <gridSetId>nyc</gridSetId>
    <zoomStart>0</zoomStart>
    <zoomStop>10</zoomStop>
    <format>image/png</format>
    <type>%s</type>
    <threadCount>1</threadCount>
    </seedRequest>
    """

    message = msgTemplate%(minX, minY, maxX, maxY, type)
    headers = { 'User-Agent' : "Python script", 'Content-type' : 'text/xml; charset="UTF-8"', 'Content-length': '%d' % len(message) }
    passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passwordManager.add_password(None, url, 'username', 'xxx')
    authenticationHandler = urllib2.HTTPBasicAuthHandler(passwordManager)
    proxyHandler = urllib2.ProxyHandler({})
    opener = urllib2.build_opener(proxyHandler, authenticationHandler)
    urllib2.install_opener(opener)    

    try :
        request = urllib2.Request(url, message, headers)
        response = urllib2.urlopen(request)
        content = response.read()
        print 'success'
    except IOError, e:
        print e

有时输出会像这样……

<urlopen error (10053, 'Software caused connection abort')>
success
success
<urlopen error (10053, 'Software caused connection abort')>
<urlopen error (10053, 'Software caused connection abort')>
...

再过1分钟运行时,输出可能会变成这样……

success
<urlopen error (10053, 'Software caused connection abort')>
success
success
<urlopen error (10053, 'Software caused connection abort')>

在这两次运行中,输入的最小/最大x/y值和类型都是相同的,并且顺序也一样。

1 个回答

0

我觉得这段代码看起来没问题,所以我不太明白出在哪里。

这里有一些建议,供你参考:

  • 我通常会先在命令行用 curl 来测试 http 请求,然后再把它转成脚本。

  • 使用 requests 库比 urllib2 更简单。

  • 当你收到响应时,打印出头信息,这样你就能看到发生了什么。

  • except IOError as e 替代 except IOError, e。新的写法能帮你避免一些难以发现的错误。

  • 我猜你已经把用户名和密码隐藏了,并在自己的脚本中使用真实的;-)

撰写回答