Scrapy笔记
安装scrapy框架
1.安装scrapy:通过pip install scrapy即可安装。
2.如果在Windows下,还需要安装pypiwin32,如果不安装,那么以后运行scrapy项目的时候就会报错
,安装方式:pip install pypiwin32.
3.如果是在Ubuntu下,还需要安装一些第三方库:studo apt-get install python-dev python-pip libxml2-dev libxt1-dev zliblg-dev libffi-dev libssl-dev.
创建项目和爬虫
1.创建项目:scrapy startproject [爬虫的名字]。
2.创建爬虫:进入到项目所在路径,执行命令:scrapy genspider [爬虫名字] [爬虫的域名]。注意,爬虫的名字不能和项目名称一致。
项目目录结构
1.iterms.py:用来存放爬虫爬取下来数据的模型。
2.middlewares.py:用来存放各种中间件的文件。
3.pipelines.py:用来将iterms的模型存储到本地磁盘中。
4.settings.py:本爬虫的一些配置信息(比如请求头、多久发送一次请求、ip代理池等)。
5.scrapy.py:项目的配置文件。
6.spiders包:以后所有的爬虫,都是存放到这个里面。
糗事百科scrapy爬虫笔记
1.response是一个scrapy.http.response.html.HtmlResponse对象,可以执行xpath和css语法来提取数据。
2.提取出来的数据,是一个Selector或者是一个SelectorList对象。如果想要获取其中的字符串。那么应该执行getall或者get方法。
3.getall方法:获取的是Selector中的所有文本,返回的是一个列表。
4.get方法:获取的是Selector中的第一个文本,返回的是一个str类型。
5.如果数据解析回来,要传给pipline处理,那么可以使用yield来返回,或者是收集所有的item,最后统一使用return返回。
6.item:建议在item.py中定义好模型。以后就不要使用字典。
7.pipline:这个是专门用来保存数据的,其中有三个方法是会经常用到的。
(1)open_spider(self, spider):当爬虫被打开的时候执行。
(2)process_item(self, spider):当爬虫有item传过来的时候会被调用。
(3)close_spider(self, spider):当爬虫关闭的时候会被调用。
要激活pipline,应该在settings.py中设置ITEM_PIPLINES。示例如下:
ITEM_PIPELINES = {
'qsbk.pipelines.QsbkPipeline': 300,
}
JsonItemExporter和JsonLinesItemExporter:
保存json数据的时候,可以使用这两个类,让操作变得更简单。
1.JsonItemExporter:这个是每次把数据添加到内存中,最后一次统一写入到磁盘中。好处是,存储的数据是一个满足json规则的数据,坏处是如果数据量比较大,那么比较耗内存。示例代码如下:
from scrapy.exporters import JsonItemExporter
class QsbkPipeline(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("爬虫结束了")
2.JsonLinesItemExporter:这个是每次调用export_item的时候把这个item存储到硬盘中。坏处是每个字典是一行,整个文件不是一个满足json格式的文件。好处是每次处理数据的时候直接存储到硬盘中,这样不会耗内存,数据也比较安全。示例代码如下:
from scrapy.exporters import JsonLinesItemExporter
class QsbkPipeline(object):
def __init__(self):
self.fp = open("duanzi.json", 'wb')
self.exporter = JsonLinesItemExporter(self.fp, ensure_ascii=False, encoding='utf-8')
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("爬虫结束了")