Python爬虫实现中断重连与断点续爬功能详解

七月
七月
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍如何在Python爬虫项目中实现中断重连与断点续爬功能,以应对网站验证或IP封禁导致的程序中断。通过维护新URL与已爬取URL集合,并将数据持久化至文件,避免内存溢出。文中提供了基于文件操作的URL管理器类及获取最后一行数据的详细代码实现,帮助开发者快速集成该功能。

爬虫中断重连需求分析

在进行爬虫项目开发时,必须考虑程序在运行过程中可能遭遇的各种异常情况,例如目标网站的人机验证或IP地址被封禁。这些情况往往导致爬虫进程意外终止。由于此前已抓取部分数据,再次启动爬虫时应当跳过已获取的内容。因此,在爬虫架构中集成中断重连机制至关重要,它允许程序在重启后从上次断点处继续执行数据抓取任务。

实现这一功能存在多种技术路径,虽然自行构建完整逻辑较为繁琐,但通过整合现有方案可以高效完成。以下展示经过整合优化的核心代码实现。

基础URL管理逻辑

首先解析该功能的核心逻辑:

系统维护两个关键数据结构:new_urls用于存储待抓取链接,old_urls用于记录已处理链接。每次成功抓取一个网址后,将其从new_urls移除并加入old_urls。在决定是否抓取某个链接时,程序会检查其所在数组状态,从而判断是否需要执行抓取操作。

内存版URL管理器实现

以下是基础实现代码(参考自其他资源):


class UrlManager(object):
  def __init__(self):  #定义两个数组
    self.new_urls=set()
    self.old_urls=set()

  def add_new_url(self, url): #将一个url加入到new_urls数组中
    if url is None:
      return
    if url not in self.new_urls and url not in self.old_urls:
      self.new_urls.add(url)

  def add_new_urls(self, urls): #将多个url加入到new_urls数组中
    if urls is None or len(urls)==0:
      return
    for url in urls :
      self.add_new_url(url)

  def has_new_url(self):  #判断url是否为空
    return len(self.new_urls)!=0

  def get_new_url(self):
    #list.pop()默认移除列表中最后一个元素对象
    new_url=self.new_urls.pop()
    self.old_urls.add(new_url)
    return new_url

文件持久化与断点续爬优化

上述类实现了基本的中断重连逻辑,但当待抓取网址数量极其庞大时,将所有URL保留在内存中会对计算机内存造成巨大压力。为此,需要将数组数据持久化保存到文件中,并增加从文件读取URL的逻辑以优化内存使用。

文件操作核心代码解析

具体实现代码如下:


class UrlManager(object):
  def __init__(self):   #建立两个数组的文件
    with open('new_urls.txt','r+') as new_urls:
      self.new_urls = new_urls.read()
    with open('old_urls.txt','r+') as old_urls:
      self.old_urls = old_urls.read()

  def add_new_url(self, url):   #添加url到new_ulrs文件中
    if url is None:
      return
    if url not in self.new_urls and url not in self.old_urls:
      with open('new_urls.txt', 'a') as new_urls:
        new_urls.write(url)
    else:
      print('url had done')

  def add_new_urls(self, urls):  #添加多个url到new_ulrs文件中
    # if urls is None or (len(url) == 0 for url in urls):
    if urls is None:
      print('url is none')
      return
    for url in urls:
      if urls is None:
        print('url is none')
        return
      else:
        self.add_new_url(url)

  def has_new_url(self):
    return len(self.new_urls) != 0

  def get_new_url(self):  
    new_url = get_last_line('new_urls.txt')  #读取new_urls文件中最后一个url
    del_last_url('new_urls.txt',new_url) #删除new_urls文件中最后一个url
    add_old_urls('old_urls.txt',new_url) #将读取出来的url添加入old_urls数组中
    return new_url

其中get_last_line()函数的实现相对复杂,这也是开发过程中耗时最长的部分,


import os
def get_last_line(inputfile):
  filesize = os.path.getsize(inputfile)
  blocksize = 1024
  dat_file = open(inputfile, 'rb')

  last_line = b""
  lines = []
  if filesize > blocksize:
    maxseekpoint = (filesize // blocksize) # 这里的除法取的是floor
    maxseekpoint -= 1
    dat_file.seek(maxseekpoint * blocksize)
    lines = dat_file.readlines()
    while ((len(lines) < 2) | ((len(lines) >= 2) & (lines[1] == b'\r\n'))): # 因为在Windows下,所以是b'\r\n'
      # 如果列表长度小于2,或者虽然长度大于等于2,但第二个元素却还是空行
      # 如果跳出循环,那么lines长度大于等于2,且第二个元素肯定是完整的行
      maxseekpoint -= 1
      dat_file.seek(maxseekpoint * blocksize)
      lines = dat_file.readlines()
  elif filesize: # 文件大小不为空
    dat_file.seek(0, 0)
    lines = dat_file.readlines()
  if lines: # 列表不为空
    for i in range(len(lines) - 1, -1, -1):
      last_line = lines[i].strip()
      if (last_line != b''):
        break # 已经找到最后一个不是空行的
  dat_file.close()
  return last_line

def del_last_url(fname,part):
  with open(fname,'rb+') as f:
    a = f.read()
  a = a.replace(part,b'')
  with open(fname,'wb+') as f:
    f.write(a)
    
def add_old_urls(fname,new_url):
  line = new_url + b'\r'
  with open(fname,'ab') as f:
    f.write(line)

至此,爬虫的中断重连功能已实现,后续只需将该模块接入主爬虫项目中即可,集成过程相对简单。

以上为本文全部内容,希望能为读者的学习提供有益参考,同时也欢迎大家继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表