Python 每5秒获取一次网页数据并运行给定时间

Python 每5秒获取一次网页数据并运行给定时间,python,web,timer,Python,Web,Timer,我想每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(

我想每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个线程

更新

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

while n > 0
time.sleep(5)
yourMethodHere()
end
但是,由于您的方法需要时间才能运行,因此请将线程创建保持在那里,并将其设置为等待0秒

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

这样,您就不会受到不良连接或其他事情的限制。

谢谢@wckd,您的回复很有帮助!我不熟悉线的东西。您能告诉我如何更改代码,使其始终使用一个线程运行吗?我刚才所做的是:在“t.start()”之后添加“time.sleep(5)”。这是正确的方法吗?它运行了15秒。但是它是同时运行3个线程,还是现在一次只运行一个线程呢?酷,看来我们的想法是一样的!您这样做的方式基本上是一次运行三个线程。但是只有三条线。主线程、运行方法的线程和排队等待在5秒内再次运行的线程。我要做的唯一进一步的更改是将计时器延迟设置为0,这将使您下降到两个线程,这对您正在尝试的操作很有好处。不知道您是否关心发布url,但如果这是私人数据,您可能希望将其隐藏在您发布的代码中