python request.get模块无法按预期工作

时间:2020-05-20 11:11:37

标签: python python-3.x

我写了一个程序来检查网址是否正常。如果站点提供404可以正常工作,但是如果站点提供503 service unavailable并给出例外,则无法正常工作。

代码:

#!/usr/bin/env python3
import smtplib
import requests
import os
from email.message import EmailMessage

x = []
f = open('sites.txt', 'r')
dns = [line.strip() for line in f]
f.close()
for obj in dns:
    try:
        url = "https://" + obj
        response = requests.get(url, timeout=10)
        if response.status_code != 200:
            print("Site is not reachable ", url)
            f = open("output.txt", "a")
            f.write(url + "\n")
            f.close()
    except requests.exceptions.ConnectionError as e:
        print("Invalid URL", e)
    except requests.exceptions.InvalidURL as e:
        print("Invalid Line", e)
if os.stat('output.txt').st_size == 0:
    print('All sites are up. Exiting..')
    exit()
else:
    with open('output.txt', 'r') as fp:
        msg = EmailMessage()
        msg.set_content(fp.read())
        msg['Subject'] = 'Alert!! following sites are not responding. Please check'
        msg['From'] = 'donotreply@admin.com'
        msg['To'] = 'niteshsinghal@admin.com'
        s = smtplib.SMTP('localhost')
        s.send_message(msg)
        s.quit()

    file = open("output.txt","r+")
    file.truncate(0)
    file.close()

当站点给出503 service unavailable时,它将转到例外,而不是出现在如果循环

输出:注意:结果中的URL是虚拟的

Invalid URL HTTPSConnectionPool(host='operations.us-east-1.stage.admin.com', port=443): Max retries exceeded with url: / (Caused by SSLError(CertificateError("hostname 'operations.us-east-1.stage.admin.com' doesn't match either of 'admin.abc.us-east-1.stage.admin.com', 'www.admin.us-east-1.stage.admin.com'",),))

请提出需要进行哪些更改,以便仅在条件条件下进入。

  1. 此外,该脚本最后在 sites.txt 中读取一个空行,且没有url,从而得到InvalidURL exception。我该如何解决呢? 但是,我暂时将其排除在外。

0 个答案:

没有答案