1. 程式人生 > >Python爬蟲之超時設定

Python爬蟲之超時設定

有時訪問一些網頁,如果該網頁長時間未響應,那麼系統會認為該網頁超時了,即無法開啟這個網頁。而有時需要我們自己來設定超時的值。

關鍵詞:timeout    設定格式urllib.request.urlopen("url",timeout=?)

程式碼:

import urllib.request

for i in range(1,100):
    try:
file = urllib.request.urlopen("http://jwc.seu.edu.cn/",timeout=1)
        data = file.read()
        print(len(data))
    except 
Exception as e: print("出現異常-->"+str(e))
設定timeout=1,即1秒訪問一次,在迴圈中一共訪問100次