我只是想更好地了解这里发生了什么,我当然可以使用 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)
http://pae.st/AxDW/显示此代码与异常/堆栈跟踪一起运行。 foo.headers
和 foo.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
谢谢。
最佳答案
此服务器既不确定又对 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 多次重新发出请求,它有时应该会成功。)
关于python - 为什么 urllib.urlopen(url) 失败而 urllib2.urlopen(url) 有效。服务器响应的具体原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9422231/