爬虫--Scrapy框架的初步使用

1.scrapy在windows环境下安装

1
2
3
4
5
6
7
8
9
10
- 环境的安装:
      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的基本使用指令

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

3.scrapy的基本配置 

1
2
3
4
5
#创建scrapy后,对settings.py进行基本配置
 
1.ROBOTSTXT_OBEY = True  #True改为False  规避robots协议
 
2.#USER_AGENT = 'first (+http://www.yourdomain.com)'  #进行UA伪装

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

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

5.scrapy的持久化存储

5.1基于终端的持久化存储

1
2
3
基于终端指令:scrapy crawl 爬虫名称 -o 文件名称.csv
- 好处:便捷
- 弊端:局限性强(只可以将数据写入本地文件,文件后缀是由具体要求)

5.2基于管道的持久化存储

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)

  

 

 

 

posted @   QV  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示