分享

python爬虫|pyspider的第一个爬虫程序,大功告成!

 Python集中营 2022-10-10 发布于甘肃
关于pyspider的安装前往查看前序文章踩坑记:终于怀着忐忑的心情完成了对 python 爬虫扩展库 pyspider 的安装

1、启动pyspider服务

1pyspider all

2、创建pyspider项目

3、项目区域说明

4、从百度首页开始爬取

  • 填写百度首页地址点击run开始爬取,点击爬取到的链接执行下一步

  • 任意点击爬取到的链接进入下一步爬取

  • 返回所进入的详情页内容

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        }



关注 Python集中营
领取编程干货
培养编程思想

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多