Python之Scrapy爬蟲框架安裝及使用詳解
題記:早已聽聞python爬蟲框架的大名。近些天學習了下其中的Scrapy爬蟲框架,將自己理解的跟大家分享。有表述不當之處,望大神們斧正。
一、初窺Scrapy
Scrapy是一個為了爬取網(wǎng)站數(shù)據(jù),提取結(jié)構(gòu)性數(shù)據(jù)而編寫的應(yīng)用框架。 可以應(yīng)用在包括數(shù)據(jù)挖掘,信息處理或存儲歷史數(shù)據(jù)等一系列的程序中。
其最初是為了 頁面抓取 (更確切來說, 網(wǎng)絡(luò)抓取 )所設(shè)計的, 也可以應(yīng)用在獲取API所返回的數(shù)據(jù)(例如 Amazon Associates Web Services ) 或者通用的網(wǎng)絡(luò)爬蟲。
本文檔將通過介紹Scrapy背后的概念使您對其工作原理有所了解, 并確定Scrapy是否是您所需要的。
當您準備好開始您的項目后,您可以參考 入門教程 。
二、Scrapy安裝介紹
Scrapy框架運行平臺及相關(guān)輔助工具
Python 2.7(Python最新版3.5,這里選擇了2.7版本)
Python Package: pip and setuptools. 現(xiàn)在 pip 依賴 setuptools ,如果未安裝,則會自動安裝setuptools 。
lxml. 大多數(shù)Linux發(fā)行版自帶了lxml。如果缺失,請查看http://lxml.de/installation.html
OpenSSL. 除了Windows(請查看 平臺安裝指南)之外的系統(tǒng)都已經(jīng)提供。
您可以使用pip來安裝Scrapy(推薦使用pip來安裝Python package).
pip install Scrapy
Windows下安裝流程:
1、安裝Python 2.7之后,您需要修改 PATH 環(huán)境變量,將Python的可執(zhí)行程序及額外的腳本添加到系統(tǒng)路徑中。將以下路徑添加到 PATH 中:
C:\Python27\;C:\Python27\Scripts\;
除此之外,還可以用cmd命令來設(shè)置Path:
c:\python27\python.exe c:\python27\tools\scripts\win_add2path.py
安裝配置完成之后,可以執(zhí)行命令python --version查看安裝的python版本。(如圖所示)

2、從 http://sourceforge.net/projects/pywin32/ 安裝 pywin32
請確認下載符合您系統(tǒng)的版本(win32或者amd64)
從 https://pip.pypa.io/en/latest/installing.html 安裝 pip
3、打開命令行窗口,確認 pip 被正確安裝:
pip --version
4、到目前為止Python 2.7 及 pip 已經(jīng)可以正確運行了。接下來安裝Scrapy:
pip install Scrapy
至此windows下Scrapy安裝已經(jīng)結(jié)束。
三、Scrapy入門教程
1、在cmd中創(chuàng)建Scrapy項目工程。
scrapy startproject tutorial
H:\python\scrapyDemo>scrapy startproject tutorial New Scrapy project 'tutorial', using template directory 'f:\\python27\\lib\\site-packages\\scrapy\\templates\\project', created in: H:\python\scrapyDemo\tutorial You can start your first spider with: cd tutorial scrapy genspider example example.com
2、文件目錄結(jié)構(gòu)如下:

解析scrapy框架結(jié)構(gòu):
scrapy.cfg: 項目的配置文件。
tutorial/: 該項目的python模塊。之后您將在此加入代碼。
tutorial/items.py: 項目中的item文件。
tutorial/pipelines.py: 項目中的pipelines文件。
tutorial/settings.py: 項目的設(shè)置文件。
tutorial/spiders/: 放置spider代碼的目錄。
3、編寫簡單的爬蟲
1)、在item.py中配置需采集頁面的字段實例。
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.item import Item, Field class TutorialItem(Item): title = Field() author = Field() releasedate = Field()
2)、在tutorial/spiders/spider.py中書寫要采集的網(wǎng)站以及分別采集各字段。
# -*-coding:utf-8-*-
import sys
from scrapy.linkextractors.sgml import SgmlLinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from tutorial.items import TutorialItem
reload(sys)
sys.setdefaultencoding("utf-8")
class ListSpider(CrawlSpider):
# 爬蟲名稱
name = "tutorial"
# 設(shè)置下載延時
download_delay = 1
# 允許域名
allowed_domains = ["news.cnblogs.com"]
# 開始URL
start_urls = [
"https://news.cnblogs.com"
]
# 爬取規(guī)則,不帶callback表示向該類url遞歸爬取
rules = (
Rule(SgmlLinkExtractor(allow=(r'https://news.cnblogs.com/n/page/\d',))),
Rule(SgmlLinkExtractor(allow=(r'https://news.cnblogs.com/n/\d+',)), callback='parse_content'),
)
# 解析內(nèi)容函數(shù)
def parse_content(self, response):
item = TutorialItem()
# 當前URL
title = response.selector.xpath('//div[@id="news_title"]')[0].extract().decode('utf-8')
item['title'] = title
author = response.selector.xpath('//div[@id="news_info"]/span/a/text()')[0].extract().decode('utf-8')
item['author'] = author
releasedate = response.selector.xpath('//div[@id="news_info"]/span[@class="time"]/text()')[0].extract().decode(
'utf-8')
item['releasedate'] = releasedate
yield item
3、在tutorial/pipelines.py管道中保存數(shù)據(jù)。
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import codecs
class TutorialPipeline(object):
def __init__(self):
self.file = codecs.open('data.json', mode='wb', encoding='utf-8')#數(shù)據(jù)存儲到data.json
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line.decode("unicode_escape"))
return item
4、tutorial/settings.py中配置執(zhí)行環(huán)境。
# -*- coding: utf-8 -*-
BOT_NAME = 'tutorial'
SPIDER_MODULES = ['tutorial.spiders']
NEWSPIDER_MODULE = 'tutorial.spiders'
# 禁止cookies,防止被ban
COOKIES_ENABLED = False
COOKIES_ENABLES = False
# 設(shè)置Pipeline,此處實現(xiàn)數(shù)據(jù)寫入文件
ITEM_PIPELINES = {
'tutorial.pipelines.TutorialPipeline': 300
}
# 設(shè)置爬蟲爬取的最大深度
DEPTH_LIMIT = 100
5、新建main文件執(zhí)行爬蟲代碼。
from scrapy import cmdline
cmdline.execute("scrapy crawl tutorial".split())
最終,執(zhí)行main.py后在data.json文件中獲取到采集結(jié)果的json數(shù)據(jù)。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python計算書頁碼的統(tǒng)計數(shù)字問題實例
這篇文章主要介紹了python計算書頁碼的統(tǒng)計數(shù)字問題實例,對比2個實例講述了數(shù)字統(tǒng)計的技巧,非常實用,需要的朋友可以參考下2014-09-09
Python調(diào)用ChatGPT的API實現(xiàn)文章生成
最近ChatGPT大火,在3.5版本后開放了接口API,所以很多人開始進行實操,這里我就用python來為大家實現(xiàn)一下,如何調(diào)用API并提問返回文章的說明2023-03-03
關(guān)于tf.TFRecordReader()函數(shù)的用法解析
今天小編就為大家分享一篇關(guān)于tf.TFRecordReader()函數(shù)的用法解析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
nginx+uwsgi+django環(huán)境搭建的方法步驟
這篇文章主要介紹了nginx+uwsgi+django環(huán)境搭建的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
ubuntu在線服務(wù)器python?Package安裝到離線服務(wù)器的過程
這篇文章主要介紹了ubuntu在線服務(wù)器python?Package安裝到離線服務(wù)器,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04

