3.1 python的scrapy框架搭建和基础介绍

python的scrapy框架搭建和基础介绍

1.安装scrapy和pypiwin32

pip install scrapy
pip install pypiwin32

注意:因为scrapy中有很多文件,所以安装scrapy时可能出现超时错误,只需要重新pip install scrapy即可,一般多次之后会安装成功。

2.创建scrapy项目和python文件

2.1创建scrapy项目:

例如我要在以下路径创建一个demo项目:在这里插入图片描述

进入cmd,cd 路径:
在这里插入图片描述
创建项目: scrap startproject [项目名]:
在这里插入图片描述

这样就创建成功了

2.2创建python文件

注意: 要进入到项目所在的路径再执行: scrapy genspider 爬虫名 “域名”
例如:
在这里插入图片描述
成功后:
在这里插入图片描述
进入pycharm可以看到:
在这里插入图片描述

3.scrapy项目的目录结构

在这里插入图片描述

过程描述:
首先,从spiders中发送一个请求给调度器scheduler,然后scheduler将这些请求存储在一个队列中,然后engine不断从scheduler中获取请求发送给downloader,然后downloader从internet中把数据下载下来,然后返回给engine,然后engine再把数据发送给spider进行解析,从中爬取有用的数据,然后发送给engine,从而储存到pipelines中。

项目目录结构:

  1. items.py :用来存放爬虫爬取下来的数据模型
  2. middlewares.oy :用来存放各种中间件文件
  3. pipelines.py :用来将items的模型存储到本地磁盘中
  4. setting.py :本爬虫的一些配置信息(比如请求头,多久发送一次请求,ip代理等)
  5. scrapy.py :项目的配置文件
  6. spiders包 :以后所有的爬虫,都存放在这个里面

3.1. spiders包 :

以后所有的爬虫,都存放在这个里面。(上一步创建的demo1.py就放在这里面。 )
这里以bsbdj.py为例展示代码:

# -*- coding: utf-8 -*-
import scrapy
from jsbk.items import JsbkItem


class BsbdjSpider(scrapy.Spider):
    name = 'bsbdj'
    allowed_domains = ['budejie.com']
    start_urls = ['http://budejie.com/']

    def parse(self, response):
       # 2.提取出来的数据时一个Selector或者是SelectorList对象, 如果想要获取其中的字符串, 应该执行getall或get方法
    # 3.getall方法: 获取的是Selector中的所有文本, 返回的是一个列表
    # 4.get方法: 获取的是Selector中的第一个文本, 返回的是str类型
        duanzi_authors = response.xpath("//a[@class = 'u-user-name']/text()")
        for duanzi_author in duanzi_authors:
            print(duanzi_author.get())
            item = JsbkItem(author = duanzi_author.get())
            yield item

3.2 setting.py 修改

1. LOG_LEVEL=“WARNING” #加入这个运行结果只会显示输出内容
2. ROBOTSTXT_OBEY = False
3. 修改请求头:添加user-agent等信息

4. 取消ITEM_PIPELINES注释

LOG_LEVEL="WARNING"
ROBOTSTXT_OBEY = False 
DEFAULT_REQUEST_HEADERS = {
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'Accept-Language': 'en',
  'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'

}

DEFAULT_REQUEST_HEADERS = {
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'Accept-Language': 'en',
    'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36',
}
ITEM_PIPELINES = {
   'jsbk.pipelines.JsbkPipeline': 300,
}

3.3 pipelines.py数据储存方式

# 储存方式1:
# import json
#
# class JsbkPipeline(object):
#     def __init__(self):
#         self.fp = open("duanzi.json",'w',encoding= 'utf-8')
#
#     def open_spider(self,spider):
#         print("爬虫开始了。。。。")
#
#     def process_item(self, item, spider):
#         item_json = json.dumps(dict(item),ensure_ascii=False)
#         self.fp.write(item_json+'\n')
#         return item
#
#     def close_spider(self,spider):
#         self.fp.close()
#         print("爬虫结束了。。。")

# #储存方式2:适用于数据较少,优点是保留json格式,缺点是数据太大占内存且容易丢失数据
# from scrapy.exporters import JsonItemExporter
#
# class JsbkPipeline(object):
#     def __init__(self):
#         self.fp = open("duanzi.json",'wb')
#         self.exporter = JsonItemExporter(self.fp,ensure_ascii = False,encoding = 'utf-8')
#         self.exporter.start_exporting()
#
#     def open_spider(self,spider):
#         print("爬虫开始了。。。。")
#
#     def process_item(self, item, spider):
#         self.exporter.export_item(item)
#         return item
#
#     def close_spider(self,spider):
#         self.exporter.finish_exporting()
#         self.fp.close()
#         print("爬虫结束了。。。")


#储存方式3:适用于数据较大,优点是不占内存,不易丢失数据,缺点是返回的是一个个字典
from scrapy.exporters import JsonLinesItemExporter     #除了JsonLinesItemExporter,还有csv等方式,ctrl+B

class JsbkPipeline(object):
    def __init__(self):
        self.fp = open("duanzi.json",'wb')
        self.exporter = JsonLinesItemExporter(self.fp,ensure_ascii = False,encoding = 'utf-8')
        self.exporter.start_exporting()

    def open_spider(self,spider):
        print("爬虫开始了。。。。")

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self,spider):
        self.fp.close()
        print("爬虫结束了。。。")

4.运行scrapy项目

在项目根目录下创建start.py文件,代码完成后点击start.py执行项目。

from scrapy import cmdline

cmdline.execute("scrapy crawl qsbk".split())
# cmdline.execute(['scrapy','crawl','qsbk'])

运行成功后会生成csv、json等文件在spider目录下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值