【发布时间】:2017-07-06 00:47:00
【问题描述】:
尝试使用请求来下载 url 列表并在它是错误 url 时捕获异常。这是我的测试代码:
import requests
from requests.exceptions import ConnectionError
#goodurl
url = "http://www.google.com"
#badurl with good host
#url = "http://www.google.com/thereisnothing.jpg"
#url with bad host
#url = "http://somethingpotato.com"
print url
try:
r = requests.get(url, allow_redirects=True)
print "the url is good"
except ConnectionError,e:
print e
print "the url is bad"
问题是如果我传入 url = "http://www.google.com" 一切都会按预期工作,因为它是一个很好的 url。
http://www.google.com
the url is good
但是如果我传入 url = "http://www.google.com/thereisnothing.jpg"
我还是明白了:
http://www.google.com/thereisnothing.jpg
the url is good
所以它几乎就像在“/”之后甚至不看任何东西
只是为了看看错误检查是否有效,我传递了一个错误的主机名:#url = "http://somethingpotato.com"
这回退了我预期的错误消息:
http://somethingpotato.com
HTTPConnectionPool(host='somethingpotato.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1b6cd15b90>: Failed to establish a new connection: [Errno -2] Name or service not known',))
the url is bad
让请求捕获错误的 url 而不仅仅是错误的主机名,我缺少什么?
谢谢
【问题讨论】:
标签: python python-2.7 download python-requests