Skip to main content

A simple crawler framework that implements both single run and distributed run based on Celery, allowing you to write your crawler code as you please

Project description

backflow

这是一个非常简洁的爬虫框架, 你可以用来写你喜欢的代码,灵活性非常高; 支持使用celery实现分布式

目录

运行平台

  • liunx / macos / windows

运行环境

  • Python 3.9+
  • liunx/windows

使用方法

安装依赖包

pip install -r requirements.txt

修改配置文件conf And settings

celery:
  host: 127.0.0.1
  port: 27017
  xxxx: xxxx

es:
  host: 127.0.0.1
  port: 9200
...

运行程序

# 查看命令帮助
backflow --help
# 查看目前所有的回流平台的爬虫列表
backflow list
# 运行单个爬虫
backflow crawl baijiahao  # Single run
backflow crawl jinritoutiao  # Single run

# Single run  The default is 20 pages. If you want to set page numbers, use the --page parameter
# For detailed parameters, please refer to the default parameter START_PAGE END_PAGE PAGE_STEP in settings.py
backflow crawl baijiahao --page 4  
# 运行所有爬虫 多线程单机运行
# main_back.py  # Can run all crawlers

分布式运行 Execute Cellery Distributed

 # 启动celery worker
celery -A tasks worker --loglevel=info 

# run distributed command / 分布式运行
backflow crawl baijiahao --distributed

# if you need to specify the number of pages for a distributed crawler, 100 pages, and a step size of 10
backflow crawl baijiahao --distributed --page 100 --step 10

添加新爬虫 新增名为newspider的爬虫

# add new spider
backflow addspider newspider

模版爬虫代码

当你使用命令backflow addspider newspider创建好一个新的spider模版后,请确保你的爬虫代码请求 可以正确采集到数据

from loguru import logger
from utils.tools import Tools
from Backflows.base import BackFlow
from Backflows.middleware import Request
import traceback


class {spider_name.capitalize()}(BackFlow):
    name = '{spider_name}'

    def __init__(self):
        super().__init__()
        self.ck = None
        self.headers = {{
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like "
                          "Gecko) Chrome/108.0.0.0 Safari/537.36"
        }}

    async def get_page_request(self, page):
        url = 'http://example.com/api/data?page={{}}'.format(page)
        return Request('GET', url=url, headers=self.headers, cookies=self.ck, meta={{'page': page}})

    async def parse(self, response):

        resp = response.json()
        datas = resp.get('data', {{}})
        if not datas:
            print(f'{spider_name} cookie might be expired or no data returned.')
            return
        for con in datas:
            news = {{
                'url': con.get('item_id', ''),
            }}
            yield news

正式服务器配置

server:
  120.xx.xx.249

demo server:
  host: 120.xx.xx.249
  path: /opt/workstation/xx/

定时任务:
  crontab/supervisor

框架运行步骤

  1. 启动程序: 在命令行中运行runner.py,并传入相应的参数,例如爬虫的名称、是否以分布式模式运行、停止页码和步长。

  2. 命令行解析argparse库解析命令行参数,并根据参数确定运行模式。

  3. 查找爬虫SpiderRunner类的find_spiders方法搜索所有已定义的爬虫模块(如spiders),并导入这些模块。它查找所有继承自BackFlow类的爬虫,并将它们存储在一个字典中,键为爬虫的名称。

  4. 加载中间件&&Settingsload_middlewares方法根据settings.MIDDLEWARES配置加载中间件。中间件包括用户代理、重试和代理中间件,它们用于修改请求和处理响应。

  5. 运行爬虫: 如果选择了分布式模式,run方法会为每个页面生成一个run_spider任务,并使用Celery将其添加到任务队列中。否则,它会为每个页面创建一个异步任务,并使用asyncio.gather等待所有任务完成。

  6. 执行任务: 在分布式模式下,Celery worker会从任务队列中获取任务并执行。每个任务都会调用async_run_spider异步函数。

  7. 获取页面请求async_run_spider函数会创建一个Page对象,并调用爬虫的get_page_request方法来获取该页面的请求对象。

  8. 处理请求process_request方法使用中间件处理请求,例如添加用户代理、设置代理等。

  9. 抓取页面fetch_page方法使用httpx.AsyncClient发送请求并获取响应。它使用信号量来限制并发请求数量。

  10. 处理响应process_response方法使用中间件处理响应,例如检查响应状态码。

  11. 解析页面: 爬虫的parse方法解析响应内容,提取数据项。对于每个提取的数据项,它会调用管道的process_item方法进行处理。

  12. 管道处理数据项: Pipeline的process_item方法将数据项存储到MongoDB或文件中。

  13. 统计信息: 爬虫会更新已抓取页面数和已发送请求数。在所有页面抓取完成后,print_stats方法会打印这些统计信息。

  14. 错误处理: 如果任何步骤出现错误,异常会被捕获,错误信息会被记录,并通过钉钉发送通知。

注意事项

  • 本项目仅供学习交流使用,未经本地测试 请不要在生产环境使用。
  • 分布式运行需要启动celery worker。
  • restart_celery.py 脚本用于监控并重启celery worker。需要在supervisor中配置或者 直接运行
  • 爬虫代码需要在backflow/spiders目录下。
  • 爬虫配置文件需要在backflow/conf目录 和 backflow/settings.py中配置。

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

backflow-0.2.2.tar.gz (24.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

backflow-0.2.2-py3-none-any.whl (32.6 kB view details)

Uploaded Python 3

File details

Details for the file backflow-0.2.2.tar.gz.

File metadata

  • Download URL: backflow-0.2.2.tar.gz
  • Upload date:
  • Size: 24.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.11.9

File hashes

Hashes for backflow-0.2.2.tar.gz
Algorithm Hash digest
SHA256 263370d6778013c075c68df2224e497db1ce2eb439694c40f82802e193eb12d7
MD5 dbeae71b0dd35d38d5bcfb197abd2d56
BLAKE2b-256 f339e83d7bf9cc1114a247f80179dfe09a78c8374a7475d3dd7469f61662363e

See more details on using hashes here.

File details

Details for the file backflow-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: backflow-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 32.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.11.9

File hashes

Hashes for backflow-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 fc7a1e53b72d3d8ef66391ae3ef225461634a898dbbe3e0e04ad74aca0bd4786
MD5 86de407d08f08b18c477495ec1e854a9
BLAKE2b-256 babbde73ca0c1774bd64dc9e5a7fdeb2fe6438f9b6edff3c3ac8560c251593ce

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page