1、启动pyspider服务 2、创建pyspider项目 3、项目区域说明 4、从百度首页开始爬取 5、代码编辑区函数 1#!/usr/bin/env python 2# -*- encoding: utf-8 -*- 3# Created on 2021-04-10 11:24:26 4# Project: test 5 6from pyspider.libs.base_handler import * 7 8# 处理类 9class Handler(BaseHandler): 10 # 爬虫相关参数配置,全局生效(字典类型) 11 crawl_config = { 12 'url':'http://www.baidu.com' 13 } 14 15 # 表示每天一次,minutes单位为分钟 16 @every(minutes=24 * 60) 17 # 程序入口 18 def on_start(self): 19 # 设置爬虫地址 20 self.crawl('http://www.baidu.com', callback=self.index_page) 21 22 # 表示10天内不会再次爬取,age单位为秒 23 @config(age=10 * 24 * 60 * 60) 24 # 回调函数、数据解析 25 def index_page(self, response): 26 # response.doc() 返回的是pyquery对象,因此采用pyquery对象解析 27 for each in response.doc('a[href^="http"]').items(): 28 # 遍历并回调爬取详情页 29 self.crawl(each.attr.href, callback=self.detail_page) 30 31 # 任务优先级设置 32 @config(priority=2) 33 # 回调函数、返回结果 34 def detail_page(self, response): 35 # 返回详情页 36 return { 37 "url": response.url, 38 "title": response.doc('title').text(), 39 }
|