首页 > 其他分享 >scrapy爬虫标准流程

scrapy爬虫标准流程

时间:2023-05-08 10:13:29浏览次数:28  
标签:url 流程 爬虫 item scrapy self def

Scrapy爬虫的标准流程一般包括以下几个步骤:

1、明确需求和目标网站的结构,确定需要爬取的数据以及爬取规则。

2、创建一个Scrapy项目,使用命令行工具创建一个新的Scrapy项目。

3、定义数据模型和item,即确定要爬取的数据结构。

4、编写爬虫类,使用Scrapy的Spider类编写爬虫程序,根据需求和目标网站的结构,确定爬取的起始URL,处理每个页面的响应数据,并根据规则提取需要的数据。

5、编写数据处理管道,对爬取的数据进行处理,包括清洗、去重、存储等操作。

6、配置Scrapy设置,包括请求头、代理、下载延迟等设置,以保证爬虫程序的稳定性和高效性。

7、运行爬虫程序,使用命令行工具运行爬虫程序,查看爬取结果。

8、调试和优化,根据爬取结果和日志信息,对爬虫程序进行调试和优化,提高爬取效率和数据质量。

总体来说,Scrapy爬虫的标准流程包括需求分析、项目创建、数据模型定义、爬虫编写、数据处理管道编写、设置配置、运行爬虫程序、调试和优化等步骤。

scrapy简介

Scrapy使用了Twisted作为框架,Twisted有些特殊的地方是它是事件驱动的,并且比较适合异步的代码。对于会阻塞线程的操作包含访问文件、数据库或者Web、产生新的进程并需要处理新进程的输出(如运行shell命令)、执行系统层次操作的代码(如等待系统队列),Twisted提供了允许执行上面的操作但不会阻塞代码执行的方法。

scrapy的项目结构:

常用命令

开始一个新的项目

scrapy startproject bing_search

命令执行后,会创建一个bing_search文件夹.

生成一个新的爬虫

scrapy genspider example Example Domain

执行命令后会在spiders文件夹中创建一个example.py的文件。

开始爬取

# tencentPosition为爬虫名
scrapy crawl tencentPosition

基本文件

items.py

负责数据模型的建立,类似于实体类。

items.py里存放的是我们要爬取数据的字段信息,代码如下:

我们分别要爬取的信息包括:文章标题,文件发布时间,文章url地址,url_object_id是我们会对地址进行md5加密,front_image_url 是文章下图片的url地址,front_image_path图片的存放路径

class JoBoleArticleItem(scrapy.Item):
    title = scrapy.Field()
    create_date = scrapy.Field()
    url = scrapy.Field()
    url_object_id = scrapy.Field()
    front_image_url = scrapy.Field()
    front_image_path = scrapy.Field()
    praise_nums = scrapy.Field()
    fav_nums = scrapy.Field()
    comment_nums = scrapy.Field()
    tag = scrapy.Field()
    content = scrapy.Field()

pipelines.py

负责对spider返回数据的处理。

pipeline主要是对spiders中爬虫的返回的数据的处理,这里我们可以让写入到数据库,也可以让写入到文件等等。

下面代码中主要包括的写入到json文件以及写入到数据库,包括异步插入到数据库,还有图片的处理,这里我们可以定义各种我们需要的pipeline,当然这里我们不同的pipeline是有一定的顺序的,需要的设置是在settings配置文件中,如下,后面的数字表示的是优先级,数字越小优先级越高。

# -*- coding: utf-8 -*-
import json
class TencentPipeline(object):
  """ 
       功能:保存item数据 
   """
    def __init__(self):
        self.filename = open("tencent.json", "w")
    def process_item(self, item, spider):
        text = json.dumps(dict(item), ensure_ascii = False) + ",\n"
        self.filename.write(text.encode("utf-8"))
        return item
    def close_spider(self, spider):
        self.filename.close()

middlewares.py

settings.py

# 设置请求头部,添加url
DEFAULT_REQUEST_HEADERS = {
    "User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;",
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
# 设置item——pipelines
ITEM_PIPELINES = {
    'tencent.pipelines.TencentPipeline': 300,
}

spiders/

负责存放继承自scrapy的爬虫类。

基础爬虫类

# -*- coding: utf-8 -*-
import scrapy
from tencent.items import TencentItem
class TencentpositionSpider(scrapy.Spider):
    """
    功能:爬取腾讯社招信息
    """
    # 爬虫名
    name = "tencentPosition"
    # 爬虫作用范围
    allowed_domains = ["tencent.com"]
    url = "http://hr.tencent.com/position.php?&start="
    offset = 0
    # 起始url
    start_urls = [url + str(offset)]
    def parse(self, response):
        for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):
            # 初始化模型对象
            item = TencentItem()
            # 职位名称
            item['positionname'] = each.xpath("./td[1]/a/text()").extract()[0]
            # 详情连接
            item['positionlink'] = each.xpath("./td[1]/a/@href").extract()[0]
            # 职位类别
            item['positionType'] = each.xpath("./td[2]/text()").extract()[0]
            # 招聘人数
            item['peopleNum'] =  each.xpath("./td[3]/text()").extract()[0]
            # 工作地点
            item['workLocation'] = each.xpath("./td[4]/text()").extract()[0]
            # 发布时间
            item['publishTime'] = each.xpath("./td[5]/text()").extract()[0]
            yield item
        if self.offset < 1680:
            self.offset += 10
        # 每次处理完一页的数据之后,重新发送下一页页面请求
        # self.offset自增10,同时拼接为新的url,并调用回调函数self.parse处理Response
        yield scrapy.Request(self.url + str(self.offset), callback = self.parse)

crawl 爬虫类

# -*- coding:utf-8 -*-
import scrapy
# 导入CrawlSpider类和Rule
from scrapy.spiders import CrawlSpider, Rule
# 导入链接规则匹配类,用来提取符合规则的连接
from scrapy.linkextractors import LinkExtractor
from TencentSpider.items import TencentItem
class TencentSpider(CrawlSpider):
    name = "tencent"
    allow_domains = ["hr.tencent.com"]
    start_urls = ["http://hr.tencent.com/position.php?&start=0#a"]
    # Response里链接的提取规则,返回的符合匹配规则的链接匹配对象的列表
    pagelink = LinkExtractor(allow=("start=\d+"))
    rules = [
        # 获取这个列表里的链接,依次发送请求,并且继续跟进,调用指定回调函数处理
        Rule(pagelink, callback = "parseTencent", follow = True)
    ]
    # 指定的回调函数
    def parseTencent(self, response):
        for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):
            item = TencentItem()
            # 职位名称
            item['positionname'] = each.xpath("./td[1]/a/text()").extract()[0]
            # 详情连接
            item['positionlink'] = each.xpath("./td[1]/a/@href").extract()[0]
            # 职位类别
            item['positionType'] = each.xpath("./td[2]/text()").extract()[0]
            # 招聘人数
            item['peopleNum'] =  each.xpath("./td[3]/text()").extract()[0]
            # 工作地点
            item['workLocation'] = each.xpath("./td[4]/text()").extract()[0]
            # 发布时间
            item['publishTime'] = each.xpath("./td[5]/text()").extract()[0]
            yield item

scrapy.cfg

scrapy基础配置

一些其他的爬虫pipeline,可能有用,比如说写入数据库等。

class JobbolespiderPipeline(object):
    def process_item(self, item, spider):
        return item
class JsonWithEncodingPipeline(object):
    '''
    返回json数据到文件
    '''
    def __init__(self):
        self.file = codecs.open("article.json",'w',encoding="utf-8")
    def process_item(self, item, spider):
        lines = json.dumps(dict(item),ensure_ascii=False) + "\n"
        self.file.write(lines)
        return item
    def spider_closed(self,spider):
        self.file.close()
class MysqlPipeline(object):
    '''
    插入mysql数据库
    '''
    def __init__(self):
        self.conn =pymysql.connect(host='192.168.1.19',port=3306,user='root',passwd='123456',db='article_spider',use_unicode=True, charset="utf8")
        self.cursor = self.conn.cursor()
    def process_item(self,item,spider):
        insert_sql = '''
        insert into jobbole_article(title,create_date,url,url_object_id,front_image_url,front_image_path,comment_nums,fav_nums,praise_nums,tag,content) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
        '''
        self.cursor.execute(insert_sql,(item["title"],item["create_date"],item["url"],item["url_object_id"],item["front_image_url"],item["front_image_path"],item["comment_nums"],item["fav_nums"],item["praise_nums"],item["tag"],item["content"]))
        self.conn.commit()
class MysqlTwistedPipline(object):
    '''
    采用异步的方式插入数据
    '''
    def __init__(self,dbpool):
        self.dbpool = dbpool
    @classmethod
    def from_settings(cls,settings):
        dbparms = dict(
            host = settings["MYSQL_HOST"],
            port = settings["MYSQL_PORT"],
            user = settings["MYSQL_USER"],
            passwd = settings["MYSQL_PASSWD"],
            db = settings["MYSQL_DB"],
            use_unicode = True,
            charset="utf8",
        )
        dbpool = adbapi.ConnectionPool("pymysql",**dbparms)
        return cls(dbpool)
    def process_item(self,item,spider):
        '''
        使用twisted将mysql插入变成异步
        :param item:
        :param spider:
        :return:
        '''
        query = self.dbpool.runInteraction(self.do_insert,item)
        query.addErrback(self.handle_error)
    def handle_error(self,failure):
        #处理异步插入的异常
        print(failure)
    def do_insert(self,cursor,item):
        #具体插入数据
        insert_sql = '''
        insert into jobbole_article(title,create_date,url,url_object_id,front_image_url,front_image_path,comment_nums,fav_nums,praise_nums,tag,content) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
        '''
        cursor.execute(insert_sql,(item["title"],item["create_date"],item["url"],item["url_object_id"],item["front_image_url"],item["front_image_path"],item["comment_nums"],item["fav_nums"],item["praise_nums"],item["tag"],item["content"]))
class ArticleImagePipeline(ImagesPipeline):
    '''
    对图片的处理
    '''
    def item_completed(self, results, item, info):
        for ok ,value in results:
            if ok:
                image_file_path = value["path"]
                item['front_image_path'] = image_file_path
            else:
                item['front_image_path'] = ""
        return item

 

标签:url,流程,爬虫,item,scrapy,self,def
From: https://www.cnblogs.com/q-q56731526/p/17380854.html

相关文章

  • 安装爬虫框架记录(第三方库)
    安装指令:python-mpipinstall.whl文件 安装Scrapy3-1.0.1,需要的依赖库如下:zope.interface>=4.4.2constantly>=15.1incremental>=21.3.0Automat>=0.8.0six-1.16.0hyperlink>=17.1.1PyHamcrest!=1.10.0,>=1.9.0Twisted>=13.1.0(最后) 安装pyOpenSSL-23.1.1......
  • Tomcat总体架构,启动流程与处理请求流程
    系列文章目录和关于我参考书籍《Tomcat架构解析》一丶Tomcat总体架构本文沿袭《Tomcat架构解析》中启发式的方式来总结Tomcat总体架构1Server假设当前我们要编写一个web应用服务器,web应用服务器最基本的功能是接受客户端发送的请求数据并进行解析,完成相关的业务处理,然后将......
  • 流程控制
    引子流程控制即控制流程,具体指控制程序的执行流程,而程序的执行流程分为三种结构:顺序结构(之前我们写的代码都是顺序结构)、分支结构(用到if判断)、循环结构(用到while与for)分支结构什么是分支结构分支结构就是根据条件判断的真假去执行不同分支对应的子代码为什么要用分支结构人......
  • Linux驱动开发笔记(一):helloworld驱动源码编写、makefile编写以及驱动编译基本流程
    前言  基于linux的驱动开发学习笔记,本篇是描述了一个字符驱动的基础开发流程,以便做嵌入式开发多年的应用或者系统学习驱动开发。 笔者自身情况  笔者拥有硬件基础,单片机软硬基础,linux系统基础等各种,就是没有linux驱动框架基础,未做过linux系统移植和驱动移植开发了......
  • 微信小程序登录的流程
    微信登录的流程移动端的知识点上面黄色代表前端小程序需要完成的过程上面紫色代表微信官方接口需要完成的过程上面蓝色代表idea服务器需要完成的过程1.用户前端/微信小程序获取随机生成的授权码code2.小程序发请求去登录(小程序携带授权码code)---从前端到后端携带授权......
  • django生命周期流程图与django路由层
    目录一、django请求生命周期流程图二、django路由层1.路由匹配2.转换器3.正则匹配不同版本的区别正则匹配斜杠导致的区别4、正则匹配的无名有名分组分组匹配无名分组有名分组三、反向解析1.引入反向解析2.反向解析使用3.有名无名反向解析(动态路由反向解析)四、路由分发五、名称空间......
  • springmvc大体工作流程
    1、用户发送HTTP请求到DispatcherServlet;2、DispatcherServlet调用HandlerMapping找到对应的处理器(类似Controller里的方法的RequestMapping),然后以HandlerExecutionChain执行链的形式返回给DispatcherServlet;3、DispatcherServlet把执行链中的Handler发送给HandlerAdapter;4、H......
  • AIGC生产工艺流程之games生产流程
    AIGC生产工艺流程中的“games生产流程”主要是指游戏的生产过程。一般来说,游戏生产流程包括游戏设计、策划、程序开发、美术制作、音效制作等等环节,具体流程可以根据不同公司和项目有所差异。其中游戏设计一般是一个较为重要的环节,主要确定游戏的整体架构和玩法规则;策划环节是根据......
  • 郑州惠济区注册公司流程和费用
    本文转载自:郑州惠济区注册公司流程和费用_郑州市惠济区办理营业执照在哪里办优账财税郑州:www.tetheme.com/zhengzhou【郑州惠济区营业执照代理多少钱(郑州市营业执照代理流程)】郑州惠济区营业执照代理一般会在网站上留下公司的联系方式(电话),方便你在线多维度筛选郑州惠济区营......
  • 爬虫JS逆向其实挺简单
    JS逆向爬虫是指通过分析网站的JavaScript代码,模拟浏览器行为,从而获取网站数据的一种方式。下面是一个JS逆向爬虫的案例:1、分析目标网站的JavaScript代码,找到数据请求的URL和参数。2、使用Python的Requests库发送模拟的HTTP请求,携带必要的参数。3、解析返回的数据,提取需要的信息......