为什么urllib.urlopen(url)在urllib2.urlopen(url)工作时失败.具体关于服务器响应的原因是什么?

sen*_*nte 8 python http urllib urllib2

我只是想更好地了解这里发生了什么,我当然可以通过使用urllib2"解决"这个问题.

import urllib
import urllib2

url = "http://www.crutchfield.com/S-pqvJFyfA8KG/p_15410415/Dynamat-10415-Xtreme-Speaker-Kit.html"

# urllib2 works fine (foo.headers / foo.read() also behave)
foo = urllib2.urlopen(url)

# urllib throws errors though, what specifically is causing this?
bar = urllib.urlopen(url)
Run Code Online (Sandbox Code Playgroud)

http://pae.st/AxDW/使用异常/ stacktrace显示此代码. foo.headersfoo.read()做工精细

stu@sente.cc~ $:curl -I "http://www.crutchfield.com/S-pqvJFyfA8KG/p_15410415/Dynamat-10415-Xtreme-Speaker-Kit.html"

HTTP/1.1 302 Object Moved
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Location: /S-FSTWJcduy5w/p_15410415/Dynamat-10415-Xtreme-Speaker-Kit.html
Server: Microsoft-IIS/7.5
Set-Cookie: SESSIONID=FSTWJcduy5w; domain=.crutchfield.com; expires=Fri, 22-Feb-2013 22:06:43 GMT; path=/
Set-Cookie: SYSTEMID=0; domain=.crutchfield.com; expires=Fri, 22-Feb-2013 22:06:43 GMT; path=/
Set-Cookie: SESSIONDATE=02/23/2012 17:07:00; domain=.crutchfield.com; expires=Fri, 22-Feb-2013 22:06:43 GMT; path=/
X-AspNet-Version: 4.0.30319
HostName: cws105
Date: Thu, 23 Feb 2012 22:06:43 GMT
Run Code Online (Sandbox Code Playgroud)

谢谢.

Gly*_*yph 7

此服务器既不确定又对HTTP版本敏感. urllib2是HTTP/1.1,urllib是HTTP/1.0.您可以通过连续运行curl --http1.0 -I "http://www.crutchfield.com/S-pqvJFyfA8KG/p_15410415/Dynamat-10415-Xtreme-Speaker-Kit.html" 几次来重现这一点.你curl: (52) Empty reply from server偶尔会看到输出; 这是错误urllib报告.(如果你多次使用urllib发出请求,它有时会成功.)