scrapy框架之基礎

1、安裝scrapy

安裝失敗看博客>>>scrapy安裝失敗解決方案html

pip install wheel
pip install twisted
pip install pywin32
pip install scrapy

2、建立爬蟲項目

scrapy startproject firstPro

# firstPro表示項目名稱

項目目錄結構

cmd命令行輸入     D:\爬蟲項目\first>tree /fpython

└─first
    │  items.py
    │  middlewares.py
    │  pipelines.py
    │  settings.py
    │  __init__.py
    │
    ├─spiders
    │  │  jingdong.py
    │  │  __init__.py
    │  │
    │  └─__pycache__
    │          jingdong.cpython-36.pyc
    │          __init__.cpython-36.pyc
    │
    └─__pycache__
            items.cpython-36.pyc
            pipelines.cpython-36.pyc
            settings.cpython-36.pyc
            __init__.cpython-36.pyc
scrapy.cfg     # scrapy部署時的配置文件
taobao         # 項目的模塊,須要從這裏引入
__init__.py    
items.py       # 定義爬取的數據結構
middlewares.py  # 定義爬取時的中間件
pipelines.py    # 定義數據管道
settings.py    # 配置文件
spiders        # 放置爬蟲的文件夾
__init__

3、建立爬蟲

# 在spiders文件夾中建立一個py文件用於網頁抓取內容並解析結果
- cmd命令行建立
- D:\爬蟲項目\taobao\taobao\spiders>scrapy genspider jingdong www.xxx.com
- jingdong爲蜘蛛名稱     www.xxx.com爲域名


# 建立的jingdong.py
import scrapy
class JingdongSpider(scrapy.Spider):
    name = 'jingdong'  # 項目惟一的名字,用來區分不一樣的spider
    allowed_domains = ['www.xxx.com']  # 容許爬取的域名
    start_urls = ['http://www.xxx.com/']  # spider啓動時抓取的url列表
    
    # 負責解析/提取/start_urls裏面請求完的響應數據
    def parse(self, response):
        pass

定義item字段

在解析數據以前咱們要在items文件中定義咱們要解析的字段,由於咱們解析完的數據須要提交到管道,而管道只接收item對象json

import scrapy

class FirstItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field()

數據爬取並解析

import scrapy
from first.items import FirstItem  # 導入items中的FirstItem類

class JingdongSpider(scrapy.Spider):
    name = 'jingdong'
    allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.cnblogs.com/songzhixue/p/10717975.html']
    
     # 管道存儲 函數名parse也是不能夠更改的
    def parse(self, response):
        tetle = response.xpath('//*[@id="cnblogs_post_body"]/ul/li/a/text()').extract()

        for name in tetle:
            # 實例化一個item對象
            item = FirstItem()
            # 將解析到的數據所有封裝到item對象中
            item["name"] = name
            yield item  # 將item提交給管道

這裏咱們使用了extrctcookie

tetle = response.xpath('//*[@id="cnblogs_post_body"]/ul/li/a/text()')
# xpath提取完是一個Selector對象
<Selector xpath='//*[@id="cnblogs_post_body"]/ul/li/a/text()' data='基礎【一】基礎數據類型'>

# 提取data數據須要加上.extract()
tetle = response.xpath('//*[@id="cnblogs_post_body"]/ul/li/a/text()').extract()  #返回值爲列表

# extract_first() #取列表中的第一項 等於extract()[0]
# 若是咱們xpath寫錯或者xpath拿不到值時咱們調用了extract_first() 則返回值爲None

4、數據持久化

 管道只接收item對象,因此咱們必須在items中給數據定義字段,並將解到的數據寫入item對象中數據結構

# 基於管道的數據持久化
# 處理jingdong爬蟲數據的管道
class FirstPipeline1(object):
    fp = None
    # 打開文件 重寫父類的方法 只會執行一次
    def open_spider(self,spider):
        print("開始爬蟲------")
        self.fp = open("./spider.txt","w",encoding="utf-8")  # 能夠定義任意文件的後綴

    def process_item(self, item, spider):
        name = item["name"]
        self.fp.write(name+"\n")
        
        return item

    def close_spider(self,spider):
        print("結束爬蟲------")
        self.fp.close()

持久化流程

items.py :數據結構模板文件,定義數據屬性
pipelines.py :管道文件,接收數據(items)進行持久化操做

- 持久化存儲
  - 基於終端指令:
    - 前提:只能夠將parse方法的返回值進行本地文件的持久化存儲
    - 指令:scrapy crawl spiderName -o filePath
  - 基於管道:
    1.數據解析
    2.須要在item類中定義相關的屬性(存儲解析到的數據)
    3.將解析到的數據存儲或者封裝到一個item類型的對象中
    4.將item對象提交到管道中
    5.在管道中須要接收item,且將item對象中的數據進行任意形式的持久化操做
    6.在配置文件中開啓管道app

終端持久化不須要開啓管道,在爬蟲文件中將解析後的數據返回便可dom

class JingdongSpider(scrapy.Spider):
    name = 'jingdong'
    allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.cnblogs.com/songzhixue/p/10717975.html']

    # 終端數據持久化存儲,只能夠存儲到磁盤
    def parse(self, response):
        tetle = response.xpath('//*[@id="cnblogs_post_body"]/ul/li/a/text()').extract()

        all_list = []
        for name in tetle:
            dic = {
                "name":name
            }
            all_list.append(dic)

        return all_list

# 在終端輸入指令便可本地化存儲
D:\爬蟲項目\first>scrapy crawl jingdong -o jingdong.csv

# 基於終端指令進行數據持久化存儲保存的格式
'json', 'jsonlines', 'jl', 'csv', 'xml', 'marshal', 'pickle'

5、打開管道

settings經常使用配置scrapy

# 請求頭配置
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36' 

# 配置文件中開啓管道
ITEM_PIPELINES = {
    # 300表示優先級,(數值越小優先級越高)
   'first.pipelines.FirstPipeline': 300,
}
# 設置日誌等級
LOG_LEVEL = 'WARNING'  
# ROBOTS協議配置
ROBOTSTXT_OBEY = False
# 是否處理cookie
COOKIES_ENABLED = False
 scrapy管道的細節處理
    - 數據的爬取和持久化存儲,將同一組數據分別存儲到不一樣的平臺
        - 一個管道類負責將數據存儲到某一個載體或者平臺中
        - 爬蟲文件提交的item只會提交給第一個被執行的管道類
        - 在管道類的process_item中的return item表示的含義就是將當前管道類接收到的item傳遞給下一個即將被執行的管道類

    - 注意:爬蟲類和管道類進行數據交互的形式
        - yild item:只能夠交互item類型的對象
        - spider參數:能夠交互任意形式的數據
- 一個爬蟲項目能夠有多個spider,每一個爬蟲的數據持久化方式可能不一樣,這時咱們就須要用到多個管道來處理不一樣爬蟲的數據存儲
# 處理jingdong爬蟲數據的管道
class FirstPipeline1(object):
    # 能夠將item類型對象中存儲的數據進行持久化存儲
    def process_item(self, item, spider):
        # spider就是爬蟲對象,經過點的方式調用jingdong爬蟲類中的屬性,判斷是哪一個爬蟲
        if spider.name == "jingdong":

            # item就是通過spider處理完傳過來的數據
            print(item["name"])   # 取值必須用中括號

            return item  # 將item傳給下一個管道

# 處理taobao爬蟲數據的管道
class FirstPipeline2(object):
    def process_item(self, item, spider):
        # spider就是爬蟲對象
        if spider.name == "taobao":
            print(item["name"])

            return item
        
# sttings配置       
ITEM_PIPELINES = {
    # 300表示優先級,(數值越小優先級越高)
   'first.pipelines.FirstPipeline1': 300,
   'first.pipelines.FirstPipeline2': 301,
}
哪一個管道的優先級高就先運行哪一個管道
多個爬蟲對應多個管道文件

6、啓動項目

# 進入項目文件夾下啓動
# 在cmd執行
scrapy crawl 爬蟲名字
scrapy crawl jingdong --nolog  # 不打印log日誌
相關文章
相關標籤/搜索