【问题标题】:python using requests with valid hostnamepython使用具有有效主机名的请求
【发布时间】: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


    【解决方案1】:

    请求不会在 404 响应中创建可抛出的异常。相反,您需要将它们过滤掉以检查状态是否为“正常”(HTTP 响应 200)

    import requests
    from requests.exceptions import ConnectionError
    
    #goodurl
    url = "http://www.google.com/nothing"
    
    #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)
        if r.status_code == requests.codes.ok:
            print "the url is good"
        else:
            print "the url is bad"
    except ConnectionError,e:
        print e
        print "the url is bad"
    

    编辑: 导入请求 从 requests.exceptions 导入 ConnectionError

    def printFailedUrl(url, response):
        if isinstance(response, ConnectionError):
            print "The url " + url + " failed to connect with the exception " + str(response)
        else:
            print "The url " + url + " produced the failed response code " + str(response.status_code)
    
    def testUrl(url):
        try:
            r = requests.get(url, allow_redirects=True)
            if r.status_code == requests.codes.ok:
                print "the url is good"
            else:
                printFailedUrl(url, r)
        except ConnectionError,e:
            printFailedUrl(url, e)
    
    def main():
        testUrl("http://www.google.com") #'Good' Url 
        testUrl("http://www.google.com/doesnotexist.jpg") #'Bad' Url with 404 response
        testUrl("http://sdjgb") #'Bad' url with inaccessable url
    
    main()
    

    在这种情况下,一个函数可以处理获取异常或传递给它的请求响应。这样,如果 url 返回一些非“好”(非 200)响应与抛出异常的不可用 url,您可以有单独的响应。希望这有你需要的信息。

    【讨论】:

    • 我希望传递实际的错误 (e),因为我想将错误写入文件。也许不是在 else 语句中打印“url is bad”,而是我可以打印 r.status_code (如果它对 else 语句来说应该是错误的)。你会建议吗?
    • @chowpay 问题在于它实际上不是错误,因此您将无法捕获要打印的错误。我建议制作一个自定义函数来打印一个“错误”url,其中可能包括 url 和状态代码。如果您想要一个示例,我可以添加到我的答案中
    • @chowpay 看看我在底部添加的代码是否满足您的需求
    • @chowpay 没问题!
    • 问题,用于“isinstance(response,ConnectionError)”,因为您正在提供函数 url 和响应。 “isinstance”如何知道您的“响应”是状态代码错误还是 ConnectionError?
    【解决方案2】:

    你想要的是检查r.status_code。在“http://www.google.com/thereisnothing.jpg”上获取r.status_code 将为您提供 404。您可以将仅 200 个代码 URL 设置为“好”的条件。

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 2019-05-10
      • 2015-08-17
      • 2016-10-20
      • 1970-01-01
      • 2019-11-30
      • 2011-04-01
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多