首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检查网站是否存在python3

检查网站是否存在python3
EN

Stack Overflow用户
提问于 2018-08-02 02:00:29
回答 1查看 4.4K关注 0票数 3

对不起,如果这是副本,我已经寻找了大约一个小时的答案,但似乎没有找到任何答案。无论如何,我有一个充满urls的文本文件,我想检查每个urls,看看它是否存在。我需要一些帮助来理解错误消息,如果有任何方法可以修复它或不同的方法,我可以使用。

这是我的代码

import requests

filepath = 'url.txt'  
with open(filepath) as fp:  
   url = fp.readline()
   count = 1
   while count != 677: #Runs through each line of my txt file
      print(url)
      request = requests.get(url) #Here is where im getting the error
      if request.status_code == 200:
          print('Web site exists')
      else:
        print('Web site does not exist')
      url = url.strip()
      count += 1 

这是输出

http://www.pastaia.co

Traceback (most recent call last):
File "python", line 9, in <module>
requests.exceptions.ConnectionError: 
HTTPConnectionPool(host='www.pastaia.co%0a', port=80): Max retries exceeded 
with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection 
object at 0x7fca82769e10>: Failed to establish a new connection: [Errno -2] 
Name or service not known',))
EN

回答 1

Stack Overflow用户

发布于 2018-08-02 02:10:00

该网站似乎不提供网络流量:http://www.pastaia.co

最有可能的是,requests模块的get()函数试图多次连接到url。它最终会达到自己的内部重试限制,在这一点上它会抛出ConnectionError异常。

我会将这一行包装在try-catch块中,以捕获错误(因此表示该网站不存在:

try:
    request = requests.get(url)
    if request.status_code == 200:
        print('Web site exists')
    else:
        print("Website returned response code: {code}".format(code=request.status_code))
except ConnectionError:
    print('Web site does not exist')
    continue;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51639585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档