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中。
项目目录结构:
- items.py :用来存放爬虫爬取下来的数据模型
- middlewares.oy :用来存放各种中间件文件
- pipelines.py :用来将items的模型存储到本地磁盘中
- setting.py :本爬虫的一些配置信息(比如请求头,多久发送一次请求,ip代理等)
- scrapy.py :项目的配置文件
- 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目录下。