使用scrapy實(shí)現(xiàn)爬網(wǎng)站例子和實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲(蜘蛛)的步驟
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from cnbeta.items import CnbetaItem
class CBSpider(CrawlSpider):
name = 'cnbeta'
allowed_domains = ['cnbeta.com']
start_urls = ['http://www.fzitv.net']
rules = (
Rule(SgmlLinkExtractor(allow=('/articles/.*\.htm', )),
callback='parse_page', follow=True),
)
def parse_page(self, response):
item = CnbetaItem()
sel = Selector(response)
item['title'] = sel.xpath('//title/text()').extract()
item['url'] = response.url
return item
實(shí)現(xiàn)蜘蛛爬蟲步驟
1.實(shí)例初級(jí)目標(biāo):從一個(gè)網(wǎng)站的列表頁(yè)抓取文章列表,然后存入數(shù)據(jù)庫(kù)中,數(shù)據(jù)庫(kù)包括文章標(biāo)題、鏈接、時(shí)間
首先生成一個(gè)項(xiàng)目:scrapy startproject fjsen
先定義下items,打開items.py:
我們開始建模的項(xiàng)目,我們想抓取的標(biāo)題,地址和時(shí)間的網(wǎng)站,我們定義域?yàn)檫@三個(gè)屬性。這樣做,我們編輯items.py,發(fā)現(xiàn)在開放目錄目錄。我們的項(xiàng)目看起來(lái)像這樣:
from scrapy.item import Item, Field
class FjsenItem(Item):
# define the fields for your item here like:
# name = Field()
title=Field()
link=Field()
addtime=Field()
第二步:定義一個(gè)spider,就是爬行蜘蛛(注意在工程的spiders文件夾下),他們確定一個(gè)初步清單的網(wǎng)址下載,如何跟隨鏈接,以及如何分析這些內(nèi)容的頁(yè)面中提取項(xiàng)目(我們要抓取的網(wǎng)站是http://www.fjsen.com/j/node_94962.htm 這列表的所有十頁(yè)的鏈接和時(shí)間)。
新建一個(gè)fjsen_spider.py,內(nèi)容如下:
#-*- coding: utf-8 -*-
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from fjsen.items import FjsenItem
class FjsenSpider(BaseSpider):
name="fjsen"
allowed_domains=["fjsen.com"]
start_urls=['http://www.fjsen.com/j/node_94962_'+str(x)+'.htm' for x in range(2,11)]+['http://www.fjsen.com/j/node_94962.htm']
def parse(self,response):
hxs=HtmlXPathSelector(response)
sites=hxs.select('//ul/li')
items=[]
for site in sites:
item=FjsenItem()
item['title']=site.select('a/text()').extract()
item['link'] = site.select('a/@href').extract()
item['addtime']=site.select('span/text()').extract()
items.append(item)
return items
name:是確定蜘蛛的名稱。它必須是獨(dú)特的,就是說(shuō),你不能設(shè)置相同的名稱不同的蜘蛛。
allowed_domains:這個(gè)很明顯,就是允許的域名,或者說(shuō)爬蟲所允許抓取的范圍僅限這個(gè)列表里面的域名。
start_urls:是一個(gè)網(wǎng)址列表,蜘蛛會(huì)開始爬。所以,第一頁(yè)將被列在這里下載。隨后的網(wǎng)址將生成先后從數(shù)據(jù)中包含的起始網(wǎng)址。我這里直接是列出十個(gè)列表頁(yè)。
parse():是蜘蛛的一個(gè)方法,當(dāng)每一個(gè)開始下載的url返回的Response對(duì)象都會(huì)執(zhí)行該函數(shù)。
這里面,我抓取每一個(gè)列表頁(yè)中的<ul>下的<li>下的數(shù)據(jù),包括title,鏈接,還有時(shí)間,并插入到一個(gè)列表中
第三步,將抓取到的數(shù)據(jù)存入數(shù)據(jù)庫(kù)中,這里就得在pipelines.py這個(gè)文件里面修改了
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
from os import path
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
class FjsenPipeline(object):
def __init__(self):
self.conn=None
dispatcher.connect(self.initialize,signals.engine_started)
dispatcher.connect(self.finalize,signals.engine_stopped)
def process_item(self,item,spider):
self.conn.execute('insert into fjsen values(?,?,?,?)',(None,item['title'][0],'http://www.fzitv.net/'+item['link'][0],item['addtime'][0]))
return item
def initialize(self):
if path.exists(self.filename):
self.conn=sqlite3.connect(self.filename)
else:
self.conn=self.create_table(self.filename)
def finalize(self):
if self.conn is not None:
self.conn.commit()
self.conn.close()
self.conn=None
def create_table(self,filename):
conn=sqlite3.connect(filename)
conn.execute("""create table fjsen(id integer primary key autoincrement,title text,link text,addtime text)""")
conn.commit()
return conn
這里我暫時(shí)不解釋,先繼續(xù),讓這個(gè)蜘蛛跑起來(lái)再說(shuō)。
第四步:修改setting.py這個(gè)文件:將下面這句話加進(jìn)去
ITEM_PIPELINES=['fjsen.pipelines.FjsenPipeline']
接著,跑起來(lái)吧,執(zhí)行:
scrapy crawl fjsen
就會(huì)在目前下生成一個(gè)data.sqlite的數(shù)據(jù)庫(kù)文件,所有抓取到的數(shù)據(jù)都會(huì)存在這里。
- Python爬蟲框架Scrapy安裝使用步驟
- 零基礎(chǔ)寫python爬蟲之使用Scrapy框架編寫爬蟲
- scrapy爬蟲完整實(shí)例
- 深入剖析Python的爬蟲框架Scrapy的結(jié)構(gòu)與運(yùn)作流程
- 講解Python的Scrapy爬蟲框架使用代理進(jìn)行采集的方法
- Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實(shí)現(xiàn)代碼
- Python的Scrapy爬蟲框架簡(jiǎn)單學(xué)習(xí)筆記
- 實(shí)踐Python的爬蟲框架Scrapy來(lái)抓取豆瓣電影TOP250
- 使用Python的Scrapy框架編寫web爬蟲的簡(jiǎn)單示例
- python爬蟲框架scrapy實(shí)戰(zhàn)之爬取京東商城進(jìn)階篇
- 淺析python實(shí)現(xiàn)scrapy定時(shí)執(zhí)行爬蟲
- Scrapy爬蟲多線程導(dǎo)致抓取錯(cuò)亂的問(wèn)題解決
相關(guān)文章
使用Python和Scribus創(chuàng)建一個(gè)RGB立方體的方法
這篇文章主要介紹了使用Python和Scribus創(chuàng)建一個(gè)RGB立方體的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
numpy數(shù)組合并和矩陣拼接的實(shí)現(xiàn)
這篇文章主要介紹了numpy數(shù)組合并和矩陣拼接的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
python框架flask表單實(shí)現(xiàn)詳解
這篇文章主要介紹了python框架flask表單實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
Python?OpenCV中常用圖片處理函數(shù)小結(jié)
在計(jì)算機(jī)視覺(jué)和圖像處理領(lǐng)域,OpenCV(Open?Source?Computer?Vision?Library)是一個(gè)非常強(qiáng)大和流行的開源庫(kù),本文將介紹一些常用的OpenCV函數(shù),希望對(duì)大家有所幫助2024-03-03
python連接遠(yuǎn)程ftp服務(wù)器并列出目錄下文件的方法
這篇文章主要介紹了python連接遠(yuǎn)程ftp服務(wù)器并列出目錄下文件的方法,實(shí)例分析了Python使用pysftp模塊的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
Python OpenCV實(shí)現(xiàn)裁剪并保存圖片
這篇文章主要為大家詳細(xì)介紹了Python OpenCV實(shí)現(xiàn)裁剪并保存圖片,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07
解決ImportError:DLL load failed while impo
在安裝pywin32后,可能會(huì)出現(xiàn)無(wú)法導(dǎo)入win32api的錯(cuò)誤,一個(gè)有效的解決方案是運(yùn)行pywin32_postinstall.py腳本,首先,打開cmd并切換到環(huán)境的Scripts文件夾,確保存在pywin32_postinstall.py文件2024-09-09

