使用request循环调用某一页面或者api时,若遇到请求超时会跳出循环停止运行,因此使用try/except来处理超时问题:
import urllib.request,re,time
url = "http://www.zhaoxugeng.cn/api/ip.php" #网页地址
while True:
try:
myPage=urllib.request.urlopen(url).read()
myPage = myPage.decode('GBK')
match = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
line = match.findall(myPage)
print (line[0])
time.sleep (5)
except:
print ("fail")
time.sleep (5)