构建网络爬虫时如何定义 sleep 函数而不使用 sleep() ?

问题描述 投票:0回答:1

定义一个crawlSleep过程。此过程将利用 datetime 模块来计算自上次抓取以来已经过去了多少天。它将保持睡眠*模式(在适当的 while 循环内),直到自上次爬网以来经过的时间少于一周。如果自上次抓取以来已经过去一周,它将启动重新抓取并更新抓取日期。但是,我必须定义经过天数函数而不使用内置函数(仅使用日期时间模块来获取当前日期。计算通过使用您自己的程序需要几天时间。请勿为此目的使用内置函数。),

现阶段Html解析不是很重要,我想学习如何定义这个函数()crawl sleep:这是我的代码:

import datetime

def get_page(url):
  try:
    import urllib.request
    page = urllib.request.urlopen(url).read()
    page = page.decode("utf-8")
    return page
  except:
    return ""


def get_next_target(page):
    start_link = page.find('<a href=')
    if start_link == -1:
        return None, 0
    start_quote = page.find('"', start_link)
    end_quote = page.find('"', start_quote+1)
    url = page[start_quote + 1:end_quote]
    return url, end_quote


def get_all_links(page):
    links = []
    while True:
      url, endpos = get_next_target(page)
      if url:
        links.append(url)
        page = page[endpos:]
      else:
        break
    return links


def union(p,q):
    for e in q:
        if e not in p:
            p.append(e)
def updateCrawlDate(index, keyword, url, date):
  for entry in index:
    if entry[0] == keyword:
      entry[entry.index(url)+1] = date
      return
  index.append([keyword, url, date])



def add_toIndex(index, keyword, url,date):### we must be also changed here
   #date = datetime.datetime.now().strftime("%d-%m-%y")
   if keyword in index:
      index[keyword].append({url,date})
      #index[keyword].append({date})
   else:
      index[keyword]=[{url}]
      index[keyword]=[{'test:'+date}]
      

def getclearpage(content):
  title = content[content.find("<title>")+7:content.find("</title>")]
  body = content[content.find("<body>")+6:content.find("</body>")]
  while body.find(">") != -1:
    start =  body.find("<")
    end =  body.find(">")
    body = body[:start] + body[end+1:]
  return title + body


def addPageToIndex(index, url, content,date):
  content = getclearpage(content)
  words = content.split()
  #date=  datetime.datetime.now().strftime("%d-%m-%y")
  for word in words:
    add_toIndex(index, word, url,date)


def crawlWeb(seed):
  tocrawl = [seed]
  crawled = []
  index = {} ### i changed list to dictionary
  global last_crawldate ##
  last_crawldate= datetime.datetime.now().strftime("%y-%m-%d")
  while tocrawl:
    page = tocrawl.pop()
    if page not in crawled:
      content = get_page(page)
      addPageToIndex(index, page, content,"LastcrawlDate:" +last_crawldate)
      union(tocrawl, get_all_links(get_page(page)))
      crawled.append(page)
  return index #, last_crawldate
ef crawlSleep(index,seed):
    global last_crawldate
    while True:
      current_time = datetime.datetime.now().strftime("%y-%m-%d")
      daysPassed = current_time - last_crawldate  ## i know that these are not the data types we need to apply on them ..  
      if daysPassed >= 7 :
            return crawlWeb(seed)
      else:
          return crawlSleep(index,seed)
python web-crawler python-datetime
1个回答
0
投票

在网络爬虫上下文中创建睡眠函数而不使用Python时间模块中的内置sleep()函数通常涉及实现延迟机制以将爬虫的执行暂停指定的持续时间。这样做通常是为了尊重服务器,不要太快地发送请求。您可以使用各种方法实现自定义睡眠功能。这里有一些方法

1。使用 time 模块(不带 sleep() 函数) 您可以手动计算程序应恢复和循环的时间,直到当前时间到达该点: 导入时间

def custom_sleep(duration):
    end_time = time.time() + duration
    while time.time() < end_time:
        continue  # Busy-waiting (not CPU efficient)

# Usage
custom_sleep(5)  # Pauses for 5 seconds

2。使用日期时间模块 与第一种方法类似,但使用 datetime 进行时间处理: 从日期时间导入日期时间,时间增量

def custom_sleep(duration):
    end_time = datetime.now() + timedelta(seconds=duration)
    while datetime.now() < end_time:
        continue  # Busy-waiting

# Usage
custom_sleep(5)  # Pauses for 5 seconds

注意事项 CPU 使用情况: 这些方法涉及忙等待,这意味着 CPU 正在主动运行循环,直到时间过去。与设计为非 CPU 密集型的 time.sleep() 相比,这效率较低。

阻塞:像time.sleep()一样,这些方法是阻塞的。如果您使用异步框架或处理多个线程,请考虑使用异步睡眠方法或特定于线程的睡眠机制。

精度:由于执行循环和其他指令所需的时间,这些方法可能不如 time.sleep() 精确。

© www.soinside.com 2019 - 2024. All rights reserved.