Python:使用请求和带有异常错误的循环来检查url是否存在

时间:2017-08-04 14:42:40

标签: python python-requests

只是想知道是否有人可以帮我调整这个循环:

我正在尝试确定url是否存在,但是当url不存在时(由于尝试查找不存在的url的错误),循环会卡住。

我已在异常条款中添加但是它引发了错误:(

非常感谢任何帮助!

Does_Exist = []
for i in range (0, len(df),1):
   X=[]
   url = df.iloc[i][0] + df.iloc[i][1]
   ret = requests.head(url)  
   except requests.exceptions.ConnectionError 
   if ret.status_code == 200: 
       X = 'Yes' 
       break
   else: 
       X = 'No'
   Does_Exist.append(X)

这是错误消息:

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.bspretail.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x00000222ABC46470>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)) 

1 个答案:

答案 0 :(得分:0)

尝试使用Try / Except结构:

    Does_Exist = []
    for i in range (0, len(df),1):
       X=[]
       try:
          url = df.iloc[i][0] + df.iloc[i][1]
          ret = requests.head(url)  
          X = 'Yes' 
       except:
         X = 'No'
       Does_Exist.append(X)