python - 为什么 urllib.urlopen(url) 失败而 urllib2.urlopen(url) 有效。服务器响应的具体原因是什么?

标签 python http urllib2 urllib

我只是想更好地了解这里发生了什么,我当然可以使用 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.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

谢谢。

最佳答案

此服务器既不确定又对 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/

相关文章:

python - 如何使用 BeautifulSoup 获取 colindex 数字?

python - 如何仅将元组内正确的值分配给变量

node.js - 您如何处理 token 安全 Web 应用程序中的导航?

ajax - 使用基于表单的身份验证时适当的未授权响应

Python:urlopen - 如果发生任何错误则跳过条目

python - 在 python 中使用 urllib2 和 Tor 拒绝连接

python urllib2 无法获取 google url

python - Process.run() 和 Process.start() 的区别

python - mapReduce 模式的最佳 python 实现是什么?

http - if-modified-since 与 if-none-match