爬虫--Scrapy框架的初步使用
阅读原文时间:2022年05月11日阅读:1

1.scrapy在windows环境下安装

- 环境的安装:
a. pip3 install wheel

  b. 下载twisted: http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted

  c. 进入下载目录,执行 pip3 install Twisted‑17.1.0‑cp35‑cp35m‑win\_amd64.whl

  d. pip3 install pywin32

  e. pip3 install scrapy

2.scrapy的基本使用指令

- 使用流程:
- 创建一个工程:scrapy startproject 工程名称
- cd 工程名称
- 创建爬虫文件:scrapy genspider 爬虫名称 初始url
- 执行:scrapy crawl 爬虫名称 #后面可以加--nolog参数

3.scrapy的基本配置

#创建scrapy后,对settings.py进行基本配置

1.ROBOTSTXT_OBEY = True #True改为False 规避robots协议

2.#USER_AGENT = 'first (+http://www.yourdomain.com)' #进行UA伪装

4.scrapy在使用xpath解析的时候使用extract进行取值 

author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()

content = div.xpath('./a/div/span//text()').extract()

5.scrapy的持久化存储

5.1基于终端的持久化存储

基于终端指令:scrapy crawl 爬虫名称 -o 文件名称.csv

  • 好处:便捷
  • 弊端:局限性强(只可以将数据写入本地文件,文件后缀是由具体要求)

5.2基于管道的持久化存储

1.在items.py文件中封装一个类似容器的东西,用于装爬取到的数据
author = scrapy.Field()
content = scrapy.Field()

2.在爬虫文件中,对爬取到的数据进行封装,并提交给管道
from qiubaiPro.items import QiubaiproItem
#实例化一个item类型的对象
item = QiubaiproItem()
#使用中括号的形式访问item对象中的属性
item['author'] = author
item['content'] = content

        #将item提交给管道  
        yield item

3.在settings中打开管道
ITEM_PIPELINES = {
'first.pipelines.FirstPipeline': 300,
}

4.在pipelines.py文件中对数据进行保存(三种保存分别是本地,redis,mysql)

import pymysql
from redis import Redis
class QiubaiproPipeline(object):
fp = None
def open_spider(self,spider):
print('开始爬虫……')
self.fp = open('./qiubai.txt','w',encoding='utf-8')
#可以将item类型的对象中存储的数据进行持久化存储
def process_item(self, item, spider):
author = item['author']
content = item['content']
self.fp.write(author+':'+content+'\n')

    return item #返回给了下一个即将被执行的管道类  
def close\_spider(self,spider):  
    print('结束爬虫!!!')  
    self.fp.close()

class MysqlPipeLine(object):
conn = None
cursor = None
def open_spider(self,spider):
self.conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='',db='qiubai',charset='utf8')
print(self.conn)

def process\_item(self, item, spider):  
    self.cursor = self.conn.cursor()  
    try:  
        self.cursor.execute('insert into qiubai values("%s","%s")'%(item\['author'\],item\['content'\]))  
        self.conn.commit()  
    except Exception as e:  
        print(e)  
        self.conn.rollback()  
    return item  
def close\_spider(self,spider):  
    self.cursor.close()  
    self.conn.close()

class RedisPipeLine(object):
conn = None
def open_spider(self,spider):
self.conn = Redis(host='127.0.0.1',port=6379)
print(self.conn)
def process_item(self,item,spider):
dic = {
'author':item['author'],
'content':item['content']
}
self.conn.lpush('qiubai',dic)