Skip to main content
 首页 » 编程设计

python之每5秒获取一次网页数据并运行给定的次数

2025年05月04日11cmt

我想每5秒获取一个网页的源代码,而且我想做多次。如3次,则总时间为3*5=15秒。我写了下面的代码:

import urllib2 
import threading 
 
def getWebSource(url): 
    usock = urllib2.urlopen(url) 
    data = usock.read() 
    usock.close() 
 
    with open("WebData.txt", "a") as myfile: 
        myfile.write(data) 
        myfile.write("\n\n") 
 
 
 
url = 'http://www.google.com/' 
n = 3 
while n>0: 
    t = threading.Timer(5.0, getWebSource,args = [url]) # set the seconds here 
    t.start() 
    n = n-1 

但是,当我运行它时,我得到的是:它只运行了 5 秒,并阅读了网页 3 次。它有什么问题?我预计它应该每 5 秒读取一次网页并重复 3 次。

#

更新:感谢@wckd,这是我的最终代码:

    import urllib2 
    import time 
    from time import gmtime, strftime 
 
    def getWebSource(url,fout,seconds,times): 
        while times > 0: 
            usock = urllib2.urlopen(url) 
            data = usock.read() 
            usock.close() 
 
            currentTime = strftime("%Y-%m-%d %H:%M:%S", gmtime()) 
            fout.write(currentTime +"\n") 
            fout.write(data) 
            fout.write("\n\n") 
            times = times - 1 
            time.sleep(seconds) 
 
 
 
url = 'http://www.google.com' 
fout = open("WebData.txt", "a") 
seconds = 5 
times = 4 
 
getWebSource(url,fout,seconds,times) 

请您参考如下方法:

threading.Timer() 方法只是创建一个在指定时间后启动的线程。当该线程等待运行时,循环继续运行。基本上你有三个线程,它们都将在 5 秒后运行。

如果您想要间距,您可以使 getWebSource 成为一个带有倒计时的递归函数,它会在新线程运行时启动它。或者,如果您想继续做您正在做的事情,您可以将 5 乘以 n 以获得间距。我不推荐这样做,因为如果您尝试 100 次,您将拥有 100 个线程。

更新

在一个线程中执行此操作的最简单方法是在循环中添加等待调用(也称为 sleep )

while n > 0 
time.sleep(5) 
yourMethodHere() 
end 

但是,由于您的方法需要时间来运行,因此请保留线程创建并将其设置为等待 0 秒。

while n > 0 
time.sleep(5) 
threading.Timer(0, yourMethodHere()) 
n = n - 1 
end 

这样一来,您就不会因为网络连接不畅或某些拖慢您速度的事情而受限。