您打算重試幾次 ?
程式如下 :
for i in listurl:
    attempts = 0
    while (attempts < 3) :
        try:
            html = requests.get(i,timeout=10)
            print(html.text)
            attempts = 3
        except:
            attempts += 1
            print('超時 %d 次 ' % attempts)
類式的方法可以自己改不一定要用 while loop
這樣其實沒有別的用意可以不用設 timeout
for i in listurl:
    try:
        html = requests.get(i,timeout=10)
        print(html.text)
    except:
        print('超時')
        html = requests.get(i)
        print(html.text)
                        如果except部分還是出現錯誤
有辦法重試到正確嗎
那就是在 except 的時候把錯誤的 url 記下來持續讓他試
但這個有可能造成無限迴圈
如果錯誤都沒有被處理的話
def restart(arr):
  while arr:
    try:
      html = requests.get(arr[0])
    except:
      # do except...
    else:
      print(html.text)
      arr.pop(0)
            
errorUrl = []
for i in listurl:
    try:
        html = requests.get(i,timeout=10)
        print(html.text)
    except:
        print('超時')
        errorUrl.append(i)
restart(errorUrl)
                    還是要用到def啊...
了解了
感謝
你也可以不用def
就存到 list
while errorUrl:
    try:
        html = requests.get(errorUrl[0])
    except:
        # do except...
    else:
        print(html.text)
        errorUrl.pop(0)