简体   繁体   English

Python:发生错误和消失时打印

[英]Python: Print when error occurs and when it disappears

I have a web scraping script that checks four sites once a minute and posts to twitter if any of the given keywords are present.我有一个 web 抓取脚本,该脚本每分钟检查四个站点,如果存在任何给定的关键字,则将其发布到 twitter。 If ConnectionError occurs, it sleeps for a minute and then tries again.如果发生 ConnectionError,它会休眠一分钟,然后重试。 I would like it to print "No internet connection" the first time the error occurs but not the second time if the error is still present when it tries again one minute later.我希望它在第一次发生错误时打印“无互联网连接”,但如果在一分钟后再次尝试时错误仍然存在,则不打印第二次。 I would also like it to print "Internet connection established" the first time it does not get a ConnectionError after previously having the Connection error.我还希望它在之前出现连接错误后第一次没有收到 ConnectionError 时打印“Internet 连接已建立”。 Here I would also like it to only print one time.在这里我也希望它只打印一次。 How should I code this?我应该如何编码? I have this so far:到目前为止我有这个:

def checksite():
    try:
        *extensive irrelevant code for web scraping and posting*

    except requests.exceptions.ConnectionError as e:
        print("No internet connection")

while True:
    checksite()
    sleep(60)

This does however print every time is is not able to connect to the internet.但是,每次打印都无法连接到互联网。

All help is appreciated!感谢所有帮助!

Try this:尝试这个:

NoInternet = 0
def checksite():
    try:
        *extensive irrelevant code for web scraping and posting*
        if NoInternet == 1:
           print("Internet connection established")
           NoInternet = 0

    except requests.exceptions.ConnectionError as e:
        if NoInternet == 0:
             print("No internet connection")
             NoInternet += 1 

while True:
    checksite()
    sleep(60)

But you have to check the tabs但是你必须检查标签

A simple solution could look like this, where checksite returns the status of the internet connection instead of printing (leaving the printing logic to the loop):一个简单的解决方案可能如下所示,其中checksite返回 Internet 连接的状态而不是打印(将打印逻辑留给循环):

def checksite():
    try:
        # *extensive irrelevant code for web scraping and posting*
        return True

    except requests.exceptions.ConnectionError as e:
        return False

was_connected = False
while True:
    connected = checksite()
    if connected and not was_connected:
        print("Internet connection established")
    elif not connected and was_connected:
        print("No internet connection")
    was_connected = connected
    sleep(60)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM