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

2、從http://sourceforge.net/projects/pywin32/安裝pywin32
請(qǐng)確認(rèn)下載符合您系統(tǒng)的版本(win32或者amd64)
從https://pip.pypa.io/en/latest/installing.html安裝pip
3、打開(kāi)命令行窗口,確認(rèn)pip被正確安裝:
pip --version
4、到目前為止Python 2.7 及pip已經(jīng)可以正確運(yùn)行了。接下來(lái)安裝Scrapy:
pip install Scrapy
至此windows下Scrapy安裝已經(jīng)結(jié)束。
三、Scrapy入門教程
1、在cmd中創(chuàng)建Scrapy項(xiàng)目工程。
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: 項(xiàng)目的配置文件。tutorial/: 該項(xiàng)目的python模塊。之后您將在此加入代碼。tutorial/items.py: 項(xiàng)目中的item文件。tutorial/pipelines.py: 項(xiàng)目中的pipelines文件。tutorial/settings.py: 項(xiàng)目的設(shè)置文件。tutorial/spiders/: 放置spider代碼的目錄。
3、編寫(xiě)簡(jiǎn)單的爬蟲(chóng)
1、在item.py中配置需采集頁(yè)面的字段實(shí)例。
# -*- 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中書(shū)寫(xiě)要采集的網(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):
# 爬蟲(chóng)名稱
name = "tutorial"
# 設(shè)置下載延時(shí)
download_delay = 1
# 允許域名
allowed_domains = ["news.cnblogs.com"]
# 開(kāi)始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()
# 當(dāng)前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ù)存儲(chǔ)到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,此處實(shí)現(xiàn)數(shù)據(jù)寫(xiě)入文件
ITEM_PIPELINES = {
'tutorial.pipelines.TutorialPipeline': 300
}
# 設(shè)置爬蟲(chóng)爬取的最大深度
DEPTH_LIMIT = 100
5、新建main文件執(zhí)行爬蟲(chóng)代碼。
from scrapy import cmdline
cmdline.execute("scrapy crawl tutorial".split())
最終,執(zhí)行main.py后在data.json文件中獲取到采集結(jié)果的json數(shù)據(jù)。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 在python3.9下如何安裝scrapy的方法
- Python3環(huán)境安裝Scrapy爬蟲(chóng)框架過(guò)程及常見(jiàn)錯(cuò)誤
- 圖文詳解python安裝Scrapy框架步驟
- 詳解Python網(wǎng)絡(luò)框架Django和Scrapy安裝指南
- 詳解Python安裝scrapy的正確姿勢(shì)
- mac下給python3安裝requests庫(kù)和scrapy庫(kù)的實(shí)例
- Python2.7下安裝Scrapy框架步驟教程
- Python3安裝Scrapy的方法步驟
- python安裝Scrapy圖文教程
- python中安裝Scrapy模塊依賴包匯總
- windows10系統(tǒng)中安裝python3.x+scrapy教程
- 在Linux系統(tǒng)上安裝Python的Scrapy框架的教程
- Python安裝Scrapy庫(kù)的常見(jiàn)報(bào)錯(cuò)解決
相關(guān)文章
python3中pip3安裝出錯(cuò),找不到SSL的解決方式
今天小編就為大家分享一篇python3中pip3安裝出錯(cuò),找不到SSL的解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
用pandas中的DataFrame時(shí)選取行或列的方法
今天小編就為大家分享一篇用pandas中的DataFrame時(shí)選取行或列的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
python使用xauth方式登錄飯否網(wǎng)然后發(fā)消息
這篇文章主要介紹了python使用xauth方式登錄飯否網(wǎng)然后發(fā)消息示例,需要的朋友可以參考下2014-04-04
python通用數(shù)據(jù)庫(kù)操作工具 pydbclib的使用簡(jiǎn)介
這篇文章主要介紹了python通用數(shù)據(jù)庫(kù)操作工具 pydbclib的使用簡(jiǎn)介,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12
Python socket網(wǎng)絡(luò)編程TCP/IP服務(wù)器與客戶端通信
這篇文章主要介紹了Python socket網(wǎng)絡(luò)編程TCP/IP服務(wù)器與客戶端通信的相關(guān)資料,這里對(duì)Scoket 進(jìn)行詳解并創(chuàng)建TCP服務(wù)器及TCP 客戶端實(shí)例代碼,需要的朋友可以參考下2017-01-01
Python深度學(xué)習(xí)實(shí)戰(zhàn)PyQt5菜單和工具欄功能作用
本文詳細(xì)解讀通過(guò) QtDesigner 創(chuàng)建主窗口、菜單欄和工具欄,并以菜單項(xiàng) “退出” 為例關(guān)聯(lián)系統(tǒng)定義的動(dòng)作處理方法。有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
Pandas數(shù)據(jù)操作分析基本常用的15個(gè)代碼片段
這篇文章主要介紹了Pandas數(shù)據(jù)操作分析基本常用的15個(gè)代碼片段,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
Python實(shí)現(xiàn)數(shù)據(jù)可視化大屏布局的示例詳解
數(shù)據(jù)可視化大屏展示需求無(wú)疑是對(duì)數(shù)據(jù)分析結(jié)果最好的詮釋,能夠使得別人能夠輕松的就理解我們的數(shù)據(jù)意圖。本文將通過(guò)pyecharts模塊來(lái)實(shí)現(xiàn),感興趣的可以了解一下2022-11-11

