Skip to main content
 首页 » 编程设计

python之跳过连接中断(网站和 BeautifulSoup)

2025年05月04日9java哥

我目前正在使用我的脚本执行此操作:

获取正文(来自源代码)并搜索一个字符串,直到找到该字符串为止。 (如果网站更新。)

不过,如果连接丢失,脚本会停止。

我的“连接”代码看起来像这样(每 20 秒在 while 循环中重复一次):

opener = urllib2.build_opener() 
opener.addheaders = [('User-agent', 'Mozilla/5.0')] 
 
url = ('url') 
openUrl = opener.open(url).read() 
 
soup = BeautifulSoup(openUrl) 

我用过 urllib2 和 BeautifulSoup。

谁能告诉我如何在连接丢失时让脚本“卡住”并查看互联网连接是否有效?然后根据答案继续。(因此,检查脚本是否可以连接,而不是查看站点是否已启动。如果以这种方式检查,脚本将停止并出现一堆错误。)

谢谢!

请您参考如下方法:

找到解决方案!

因此,在实际执行操作之前,我需要检查每个 LOOP 的连接。

所以我创建了这个函数:

def check_internet(self): 
    try: 
        header = {"pragma" : "no-cache"} 
        req = urllib2.Request("http://www.google.ro", headers=header) 
        response = urllib2.urlopen(req,timeout=2) 
        return True 
    except urllib2.URLError as err: 
        return False 

它有效,在我的连接断断续续的情况下对其进行了测试!

对于其他新手的纠结:

while True: 
     conn = check_internet('Site or just Google, just checking for connection.') 
     try: 
         if conn is True: 
         #code 
         else: 
         #need to make it wait and re-do the while. 
         time.sleep(30) 
     except: urllib2.URLError as err: 
         #need to wait 
         time.sleep(20) 

完美运行,脚本现在已经运行了大约 10 个小时,并且完美地处理了错误!它也适用于我的连接关闭并显示正确的消息。

接受优化建议!