使用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://chabaoo.cn']
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)目看起來像這樣:
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ú)特的,就是說,你不能設(shè)置相同的名稱不同的蜘蛛。
allowed_domains:這個(gè)很明顯,就是允許的域名,或者說爬蟲所允許抓取的范圍僅限這個(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://chabaoo.cn/'+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è)蜘蛛跑起來再說。
第四步:修改setting.py這個(gè)文件:將下面這句話加進(jìn)去
ITEM_PIPELINES=['fjsen.pipelines.FjsenPipeline']
接著,跑起來吧,執(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來抓取豆瓣電影TOP250
- 使用Python的Scrapy框架編寫web爬蟲的簡(jiǎn)單示例
- python爬蟲框架scrapy實(shí)戰(zhàn)之爬取京東商城進(jìn)階篇
- 淺析python實(shí)現(xiàn)scrapy定時(shí)執(zhí)行爬蟲
- Scrapy爬蟲多線程導(dǎo)致抓取錯(cuò)亂的問題解決
相關(guān)文章
利用Selenium添加cookie實(shí)現(xiàn)自動(dòng)登錄的示例代碼(fofa)
這篇文章主要介紹了利用Selenium添加cookie實(shí)現(xiàn)自動(dòng)登錄的示例代碼(fofa),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Pycharm中安裝Pygal并使用Pygal模擬擲骰子(推薦)
這篇文章主要介紹了Pycharm中安裝Pygal并使用Pygal模擬擲骰子,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04Python演化計(jì)算基準(zhǔn)函數(shù)詳解
這篇文章主要介紹了Python演化計(jì)算基準(zhǔn)函數(shù),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧,希望能夠給你帶來幫助2021-10-10Python Json數(shù)據(jù)文件操作原理解析
這篇文章主要介紹了Python Json數(shù)據(jù)文件操作原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05Python有關(guān)Unicode UTF-8 GBK編碼問題詳解
本文主要介紹了Python有關(guān)Unicode UTF-8 GBK編碼問題詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Windows環(huán)境下python環(huán)境安裝使用圖文教程
這篇文章主要為大家詳細(xì)介紹了Windows環(huán)境下python安裝使用圖文教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03Python報(bào)錯(cuò):對(duì)象不存在此屬性的解決
這篇文章主要介紹了Python報(bào)錯(cuò):對(duì)象不存在此屬性的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05