使用scrapy實現(xiàn)爬網(wǎng)站例子和實現(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.dbjr.com.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
實現(xiàn)蜘蛛爬蟲步驟
1.實例初級目標:從一個網(wǎng)站的列表頁抓取文章列表,然后存入數(shù)據(jù)庫中,數(shù)據(jù)庫包括文章標題、鏈接、時間
首先生成一個項目:scrapy startproject fjsen
先定義下items,打開items.py:
我們開始建模的項目,我們想抓取的標題,地址和時間的網(wǎng)站,我們定義域為這三個屬性。這樣做,我們編輯items.py,發(fā)現(xiàn)在開放目錄目錄。我們的項目看起來像這樣:
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()
第二步:定義一個spider,就是爬行蜘蛛(注意在工程的spiders文件夾下),他們確定一個初步清單的網(wǎng)址下載,如何跟隨鏈接,以及如何分析這些內(nèi)容的頁面中提取項目(我們要抓取的網(wǎng)站是http://www.fjsen.com/j/node_94962.htm 這列表的所有十頁的鏈接和時間)。
新建一個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:是確定蜘蛛的名稱。它必須是獨特的,就是說,你不能設(shè)置相同的名稱不同的蜘蛛。
allowed_domains:這個很明顯,就是允許的域名,或者說爬蟲所允許抓取的范圍僅限這個列表里面的域名。
start_urls:是一個網(wǎng)址列表,蜘蛛會開始爬。所以,第一頁將被列在這里下載。隨后的網(wǎng)址將生成先后從數(shù)據(jù)中包含的起始網(wǎng)址。我這里直接是列出十個列表頁。
parse():是蜘蛛的一個方法,當每一個開始下載的url返回的Response對象都會執(zhí)行該函數(shù)。
這里面,我抓取每一個列表頁中的<ul>下的<li>下的數(shù)據(jù),包括title,鏈接,還有時間,并插入到一個列表中
第三步,將抓取到的數(shù)據(jù)存入數(shù)據(jù)庫中,這里就得在pipelines.py這個文件里面修改了
# 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.dbjr.com.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
這里我暫時不解釋,先繼續(xù),讓這個蜘蛛跑起來再說。
第四步:修改setting.py這個文件:將下面這句話加進去
ITEM_PIPELINES=['fjsen.pipelines.FjsenPipeline']
接著,跑起來吧,執(zhí)行:
scrapy crawl fjsen
就會在目前下生成一個data.sqlite的數(shù)據(jù)庫文件,所有抓取到的數(shù)據(jù)都會存在這里。
- Python爬蟲框架Scrapy安裝使用步驟
- 零基礎(chǔ)寫python爬蟲之使用Scrapy框架編寫爬蟲
- scrapy爬蟲完整實例
- 深入剖析Python的爬蟲框架Scrapy的結(jié)構(gòu)與運作流程
- 講解Python的Scrapy爬蟲框架使用代理進行采集的方法
- Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實現(xiàn)代碼
- Python的Scrapy爬蟲框架簡單學(xué)習(xí)筆記
- 實踐Python的爬蟲框架Scrapy來抓取豆瓣電影TOP250
- 使用Python的Scrapy框架編寫web爬蟲的簡單示例
- python爬蟲框架scrapy實戰(zhàn)之爬取京東商城進階篇
- 淺析python實現(xiàn)scrapy定時執(zhí)行爬蟲
- Scrapy爬蟲多線程導(dǎo)致抓取錯亂的問題解決
相關(guān)文章
利用Selenium添加cookie實現(xiàn)自動登錄的示例代碼(fofa)
這篇文章主要介紹了利用Selenium添加cookie實現(xiàn)自動登錄的示例代碼(fofa),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Pycharm中安裝Pygal并使用Pygal模擬擲骰子(推薦)
這篇文章主要介紹了Pycharm中安裝Pygal并使用Pygal模擬擲骰子,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04Python Json數(shù)據(jù)文件操作原理解析
這篇文章主要介紹了Python Json數(shù)據(jù)文件操作原理解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05Python有關(guān)Unicode UTF-8 GBK編碼問題詳解
本文主要介紹了Python有關(guān)Unicode UTF-8 GBK編碼問題詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Windows環(huán)境下python環(huán)境安裝使用圖文教程
這篇文章主要為大家詳細介紹了Windows環(huán)境下python安裝使用圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03