搜 索

Scrapy从入门到放弃

  • 169阅读
  • 2022年06月12日
  • 0评论
首页 / 爬虫 / 正文

什么是爬虫?

爬虫是一种信息采集的技术,像google百度等搜索引擎就有着无数的爬虫基于各种规则来获取网络内容并处理,在一个新的内容发布后,很快就会被搜索引擎侦测,获取相关内容放到结果中。
在当前的环境下,大数据成为企业最重要的资产之一,对于大数据的获取、处理和分析,以及基于大数据的应用,成为企业的核心竞争力。爬虫正好可以作为重要的数据来源,作为舆情分析平台企业可以获取新闻列表并做趋势分析,作为比价平台可以爬虫获取淘宝京东pdd的商品信息供客户对比选择,而作为信息服务商可以爬取某些公开信息并辅以一些私密信息打包作为数据产品对外售卖,爬虫的应用多种多样,下面让我们来一探地表最强爬虫-scrapy面纱下的真面目。

为什么是Scrapy

Scrapy基于Twisted异步处理框架,功能强大、效率高、扩展组件多、模块化开发容易、几乎可以满足所有爬虫需求。
Scrapy架构图如下:
Scrapy架构图
从上图可看出他分为几块内容:

  • Engine 核心引擎
  • Item 定义了爬取的数据结构,类似于pojo对象
  • Scheduler 调度器,负责请求的调度
  • Downloader 下载器,下载页面内容
  • Item Pipeline 管道,清洗验证和存储数据
  • Downloader Middlewares 下载器中间件,处理引擎和下载器之间的请求和响应
  • Spider Middlewares 处理爬虫输入的响应和输出结果,以及新请求

如何使用Scrapy

项目创建

scrapy starproject tutorial
cd tutorial
scrapy genspider quotes quotes.toscrpae.com

这时项目就创建好了

举个简单的🌰

在支付公司中,会需要用到一个叫做Swift Code的东西,这是一个在跨银行转账中需要用到的银行标识参数,我们可以使用Scrapy来获取公开的此类信息。
首先我们找到一个网站是https://www.theswiftcodes.com,在这里有各个国家的SwiftCode信息,而且最主要的是他没有什么反爬措施,我们可以随心所欲的想怎么爬就怎么爬。
首先新建爬虫项目:

scrapy startproject SwiftCode
cd SwiftCode
# 新建爬虫,爬虫名 网站地址
scrapy genspider bankCodes www.theswiftcodes.com

接下来我们以爬取新加坡的SwiftCode为例,以下为爬虫代码

import scrapy

# 主要获取银行,国家,城市,swiftCode等信息
class SwiftCodeItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    id = scrapy.Field()
    bank = scrapy.Field()
    country = scrapy.Field()
    city = scrapy.Field()
    branch = scrapy.Field()
    swiftCode = scrapy.Field()


from SwiftCode.items import SwiftCodeItem

# 爬虫的实现
class BankcodesSpider(scrapy.Spider):
    name = 'bankCodes'
    allowed_domains = ['www.theswiftcodes.com']
    start_urls = ['https://www.theswiftcodes.com/singapore/']

    def parse(self, response):
        # 获取页面中的列表参数
        for quote in response.css('table.swift-country tbody tr'):
            item = SwiftCodeItem()
            # 逐项元素获取
            item['id'] = quote.css('td:nth-child(1)::text').extract_first()
            item['bank'] = quote.css('td:nth-child(2)::text').extract_first()
            item['country'] = 'SG'

            item['city'] = quote.css('td:nth-child(3)::text').extract_first()
            item['branch'] = quote.css('td:nth-child(4)::text').extract_first()
            item['swiftCode'] = quote.css('td:nth-child(5) a::text').extract_first()
            print(quote)
            
            yield item
        # next_page = response.css("div.navigation span.current").next(".page-link a::attr(href)").extract_first()
        # print("next_page")
        # print(next_page)
        print("responseUrl")
        print(response.url)
        # 爬取下一页
        pos = str(response.url).index("/", len(str(response.url))-5)
        page = str(response.url)[pos+1:]
        if page[-1:] == '/':
            page = page[:-1]
        if not page:
            yield scrapy.Request("https://www.theswiftcodes.com/singapore/page/2/", callback=self.parse)
            
        if page and page.isdigit() and int(page)<8:
            yield scrapy.Request("https://www.theswiftcodes.com/singapore/page/%s/" % (int(page)+1), callback=self.parse)

在pipelines.py中设置爬虫的pipeline

ITEM_PIPELINES = {
    # 'SwiftCode.pipelines.textPipeline':300,
    'spiders.pipelines.MysqlPipeline': 400
}

爬取之后,我们需要将数据存储起来


class MysqlPipeline(object):
    """
    同步操作
    """

    def __init__(self):
        # 建立连接
        self.conn = pymysql.connect('localhost', 'ufs', 'ufs', 'bankcodes')  # 有中文要存入数据库的话要加charset='utf8'
        # 创建游标
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        # sql语句
        insert_sql = """
        insert into swift_code(data_id,bank,country,city,branch,swift_code,gmt_create) VALUES(%s,%s,%s,%s,%s,%s,now())
        """
        print("hello22")
        print(insert_sql)

        # 执行插入数据到数据库操作
        self.cursor.execute(insert_sql, (item['id'], item['bank'], item['country'], item['city'],
                                         item['branch'], item['swiftCode']))
        # 提交,不进行提交无法保存到数据库
        self.conn.commit()
        return item

    def close_spider(self, spider):
        # 关闭游标和连接
        self.cursor.close()

然后我们来运行一下这个爬虫

scrapy crawl bankCodes

从控制台我们可以看到打印的日志和爬虫的请求响应。

Scrapy的最佳实践--构建企业级爬虫平台

附言

爬虫在国内目前是一门比较敏感的技术,

参考资料

《Python3网络爬虫开发实战》

评论区
暂无评论
avatar