Python 网络爬虫笔记10 -- Scrapy 使用入门
生活随笔
收集整理的這篇文章主要介紹了
Python 网络爬虫笔记10 -- Scrapy 使用入门
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python 網絡爬蟲筆記10 – Scrapy 使用入門
Python 網絡爬蟲系列筆記是筆者在學習嵩天老師的《Python網絡爬蟲與信息提取》課程及筆者實踐網絡爬蟲的筆記。
課程鏈接:Python網絡爬蟲與信息提取
參考文檔:
Requests 官方文檔(英文)
Requests 官方文檔(中文)
Beautiful Soup 官方文檔
re 官方文檔
Scrapy 官方文檔(英文)
Scrapy 官方文檔(中文)
一、Scrapy 使用簡化步驟
1、建立一個 Scrapy 爬蟲工程
# 打開 cmd ,cd到要創建工程的目錄,輸入命令 scrapy startproject scrapy_demo工程的文件結構:
scrapy_demo/ # 工程根目錄scrapy.cfg # 部署Scrapy爬蟲的配置文件scrapy_demo/ # Scrapy框架的用戶自定義Python代碼__pycache__/ # 緩存目錄,無需修改spiders/ # piders代碼模板目錄(繼承類),此目錄下可添加自定義的spider代碼__init__.py # 初始文件,無需修改__pycache__/ # 緩存目錄,無需修改__init__.py # 初始化腳本items.py # Items代碼模板(繼承類)middlewares.py # Middlewares代碼模板(繼承類)pipelines.py # Pipelines代碼模板(繼承類)settings.py # Scrapy爬蟲的配置文件2、在工程中產生一個Scrapy爬蟲
作用:
- 生成一個名稱為demo的spider
- 在 spiders 目錄下增加代碼文件 demo.py
- 該命令僅用于生成 demo.py,該文件也可以手工生成
自動生成的 demo.py :
# -*- coding: utf-8 -*- import scrapyclass DemoSpider(scrapy.Spider):name = 'demo'allowed_domains = ['python123.io']start_urls = ['http://python123.io/ws/demo.html']# 處理響應,解析由Downloader生成Response對象def parse(self, response):pass3、配置產生的spider爬蟲
配置內容:
- 設置初始URL地址
- 編寫獲取頁面后的解析方法
修改后的 demo.py(普通版):
# -*- coding: utf-8 -*- import scrapyclass DemoSpider(scrapy.Spider):"""普通版"""name = 'demo'# allowed_domains = ['python123.io']start_urls = ['http://python123.io/ws/demo.html']# 解析Response對象,保存HTML文件def parse(self, response):file_name = response.url.split('/')[-1]with open(file_name, 'wb') as f:f.write(response.body)self.log('Saved file %s.' % file_name)修改后的 demo.py(yield版):
# -*- coding: utf-8 -*- import scrapyclass DemoSpider(scrapy.Spider):"""yield 版"""name = 'demo'def start_requests(self):urls = ['http://python123.io/ws/demo.html']for url in urls:yield scrapy.Request(url=url, callback=self.parse)def parse(self, response):file_name = response.url.split('/')[-1]with open(file_name, 'wb') as f:f.write(response.body)self.log('Saved file %s.' % file_name)4、運行爬蟲,獲取網頁
# 打開 cmd ,cd到 Scrapy工程的目錄,輸入命令 scrapy crawl demo二、Scrapy 使用標準步驟
三、Scrapy 數據類型
1、Request 類:class scrapy.http.Request()
- Request對象表示一個HTTP請求,由Spider生成,由Downloader執行
| .url | Request對應的請求URL地址 |
| .method | 對應的請求方法,‘GET’ 'POST’等 |
| .headers | 字典類型風格的請求頭 |
| .body | 請求內容主體,字符串類型 |
| .meta | 用戶添加的擴展信息,在Scrapy內部模塊間傳遞信息使用 |
| .copy() | 復制該請求 |
2、Response 類:class scrapy.http.Response()
- Response對象表示一個HTTP響應,由Downloader生成,由Spider處理
| .url | Response對應的URL地址 |
| .status | HTTP狀態碼,默認是200 |
| .headers | Response對應的頭部信息 |
| .body | Response對應的內容信息,字符串類型 |
| .flags | 一組標記 |
| .request | 產生Response類型對應的Request對象 |
| .copy() | 復制該響應 |
3、Item 類:class scrapy.item.Item()
- Item對象表示一個從HTML頁面中提取的信息內容,由Spider生成,由Item Pipeline處理
- Item類似字典類型,可以按照字典類型操作
四、CSS Selector
- 用來檢索HTML網頁的內容
總結
以上是生活随笔為你收集整理的Python 网络爬虫笔记10 -- Scrapy 使用入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 网络爬虫笔记9 -- Sc
- 下一篇: Python 网络爬虫笔记11 -- S