Scrapy學(xué)習(xí)筆記(2)-使用pycharm在虛擬環(huán)境中運(yùn)行第一個(gè)spider

前言

系統(tǒng)環(huán)境:CentOS7

本文假設(shè)你已經(jīng)安裝了virtualenv瑞眼,并且已經(jīng)激活虛擬環(huán)境ENV1铅祸,如果沒有誓沸,請(qǐng)參考這里:使用virtualenv創(chuàng)建python沙盒(虛擬)環(huán)境

目標(biāo)

使用scrapy的命令行工具創(chuàng)建項(xiàng)目以及spider跷敬,使用Pycharm編碼并在虛擬環(huán)境中運(yùn)行spider抓取http://quotes.toscrape.com/中的article和author信息, 將抓取的信息存入txt文件麻车。

正文

1.使用命令行工具創(chuàng)建項(xiàng)目并指定項(xiàng)目路徑逆趋,具體用法為

scrapy startproject [project_dir]

項(xiàng)目名稱

[project_dir]項(xiàng)目路徑盏阶,缺省時(shí)默認(rèn)為當(dāng)前路徑

本文中quotes為項(xiàng)目名稱,PycharmProjects/quotes為項(xiàng)目路徑

(ENV1) [eason@localhost ~]$scrapy startprojectquotesPycharmProjects/quotes

New Scrapy project 'quotes', using template directory '/home/eason/ENV1/lib/python2.7/site-packages/scrapy/templates/project', created in:

/home/eason/PycharmProjects/quotes

You can start your first spider with:

cd PycharmProjects/quotes

scrapy genspider example example.com

(ENV1) [eason@localhost ~]$

2.進(jìn)入項(xiàng)目路徑并創(chuàng)建spider,命令的具體用法為

scrapy genspider [-t template]

[-t template] 指定生成spider的模板闻书,可用模板有如下4種名斟,缺省時(shí)默認(rèn)為basic

basic

crawl

csvfeed

xmlfeed

設(shè)定spider的名字

設(shè)定allowed_domains和start_urls

本文的spider名稱為quotes_spider

(ENV1) [eason@localhost ~]$cd PycharmProjects/quotes

(ENV1) [eason@localhost quotes]$scrapy genspiderquotes_spiderquotes.toscrape.com

Created spider 'quotes_spider' using template 'basic' in module:

quotes.spiders.quotes_spider

(ENV1) [eason@localhost quotes]$

至此,創(chuàng)建項(xiàng)目以及spider的工作已經(jīng)完成了魄眉。

3.在Pycharm中打開上面剛剛創(chuàng)建的項(xiàng)目


紅框內(nèi)為我們剛才創(chuàng)建項(xiàng)目的目錄結(jié)構(gòu)

├── quotes

│? └── spiders

│? ? ? └── __init__.py

|? ? ? └── quotes_spider.py

│? ├── __init__.py

│? ├── items.py

│? ├── pipelines.py

│? ├── settings.py

└── scrapy.cfg

參考官網(wǎng)文檔的解釋如下:

quotes/

project's Python module, you'll import your code from here(該項(xiàng)目的python模塊砰盐。之后您將在此加入代碼。)

quotes/spiders/

a directory where you'll later put your spiders(放置spider代碼的目錄.用來將網(wǎng)頁爬下來)

quotes/spiders/quotes_spider.py

剛才自動(dòng)生成的spider文件

quotes/items.py

project items definition file(項(xiàng)目中的item文件,其實(shí)就是要抓取的數(shù)據(jù)的結(jié)構(gòu)定義)

quotes/pipelines.py

project pipelines file(項(xiàng)目的pipelines文件坑律,在這里可以定義將抓取的數(shù)據(jù)以何種方式保存)

quotes/settings.py

project settings file(項(xiàng)目的設(shè)置文件)

scrapy.cfg

deploy configuration file(項(xiàng)目配置文件)

4.此時(shí)打開quotes_spider.py 文件會(huì)報(bào)錯(cuò)岩梳,提示找不到scrapy的模塊,這是因?yàn)楫?dāng)前pycharm是在全局環(huán)境打開該項(xiàng)目晃择,而我全局環(huán)境并沒有安裝scrapy冀值,所以下面更改項(xiàng)目設(shè)置,讓pycharm能使用虛擬環(huán)境的包和模塊


依次點(diǎn)擊菜單欄的File-->Settings打開設(shè)置界面宫屠,Project Interpreter下拉選擇當(dāng)前已經(jīng)激活的虛擬環(huán)境列疗,可能你那邊的路徑不一樣,本文是/home/eason/ENV1/bin/python

選好以后點(diǎn)擊OK浪蹂,重新打開quotes_spider.py發(fā)現(xiàn)已經(jīng)不報(bào)錯(cuò)了抵栈。

5.編輯items.py定義數(shù)據(jù)結(jié)構(gòu)

# -*- 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

class QuotesItem(scrapy.Item):

# define the fields for your item here like:

# name = scrapy.Field()

article=scrapy.Field()

author=scrapy.Field()

pass

5.編輯quotes_spider.py添加爬取規(guī)則

# -*- coding: utf-8 -*-

import scrapy

from ..items import QuotesItem

class QuotesSpiderSpider(scrapy.Spider):

name = "quotes_spider"

allowed_domains = ["quotes.toscrape.com"]

start_urls = ['http://quotes.toscrape.com/']

def parse(self, response):

items=[]

articles=response.xpath("http://div[@class='quote']")

for article in articles:

item=QuotesItem()

content=article.xpath("span[@class='text']/text()").extract_first()

author=article.xpath("span/small[@class='author']/text()").extract_first()

item['article']=content.encode('utf-8')

item['author'] = author.encode('utf-8')

items.append(item)

return items

6.編輯pipelines.py,確定數(shù)據(jù)保存方法坤次,本文為寫到文本文件result.txt中

# -*- 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

class QuotesPipeline(object):

def process_item(self, item, spider):

#爬取的數(shù)據(jù)保存在/home/eason/PycharmProjects/quotes/路徑下

f = open(r"/home/eason/PycharmProjects/quotes/result.txt", "a")

f.write(item['article']+'\t' +item['author']+'\n')

f.close()

return item

7.為了讓pipeline.py生效古劲,還需要在settings.py文件中注冊(cè)

# -*- coding: utf-8 -*-

# Scrapy settings for quotes project

#

# For simplicity, this file contains only settings considered important or

# commonly used. You can find more settings consulting the documentation:

#

#? ? http://doc.scrapy.org/en/latest/topics/settings.html

#? ? http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html

#? ? http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'quotes'

SPIDER_MODULES = ['quotes.spiders']

NEWSPIDER_MODULE = 'quotes.spiders'

# Obey robots.txt rules

ROBOTSTXT_OBEY = True

# Configure item pipelines

# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html

ITEM_PIPELINES = {

'quotes.pipelines.QuotesPipeline': 300,

}

8.在Pycharm中打開Terminal,激活虛擬環(huán)境并運(yùn)行spider

[eason@localhost quotes]$source /home/eason/ENV1/bin/activate

(ENV1) [eason@localhost quotes]$scrapy crawl quotes_spider

9.爬取完成后缰猴,會(huì)在/home/eason/PycharmProjects/quotes/路徑下生成result.txt文件产艾,打開result.txt后內(nèi)容如下

10.Done!

更多原創(chuàng)文章,盡在金筆頭博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末滑绒,一起剝皮案震驚了整個(gè)濱河市闷堡,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蹬挤,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,651評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件棘幸,死亡現(xiàn)場(chǎng)離奇詭異焰扳,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門吨悍,熙熙樓的掌柜王于貴愁眉苦臉地迎上來扫茅,“玉大人,你說我怎么就攤上這事育瓜『叮” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵躏仇,是天一觀的道長(zhǎng)恋脚。 經(jīng)常有香客問我,道長(zhǎng)焰手,這世上最難降的妖魔是什么糟描? 我笑而不...
    開封第一講書人閱讀 58,218評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮书妻,結(jié)果婚禮上船响,老公的妹妹穿的比我還像新娘。我一直安慰自己躲履,他們只是感情好见间,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著工猜,像睡著了一般米诉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上域慷,一...
    開封第一講書人閱讀 51,198評(píng)論 1 299
  • 那天荒辕,我揣著相機(jī)與錄音,去河邊找鬼犹褒。 笑死抵窒,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的叠骑。 我是一名探鬼主播李皇,決...
    沈念sama閱讀 40,084評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼宙枷!你這毒婦竟也來了掉房?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,926評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤慰丛,失蹤者是張志新(化名)和其女友劉穎卓囚,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體诅病,經(jīng)...
    沈念sama閱讀 45,341評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡哪亿,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評(píng)論 2 333
  • 正文 我和宋清朗相戀三年粥烁,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蝇棉。...
    茶點(diǎn)故事閱讀 39,731評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡讨阻,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出篡殷,到底是詐尸還是另有隱情钝吮,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評(píng)論 5 343
  • 正文 年R本政府宣布板辽,位于F島的核電站奇瘦,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏戳气。R本人自食惡果不足惜链患,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望瓶您。 院中可真熱鬧麻捻,春花似錦、人聲如沸呀袱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽夜赵。三九已至明棍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間寇僧,已是汗流浹背摊腋。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留嘁傀,地道東北人兴蒸。 一個(gè)月前我還...
    沈念sama閱讀 47,743評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像细办,于是被迫代替她去往敵國和親橙凳。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容