這篇文章給大家分享的是有關(guān)python爬蟲(chóng)中怎樣編寫(xiě)pyspider的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧。
代碼:
from pyspider.libs.base_handler import *class Handler(BaseHandler): crawl_config = { } @every(minutes=24 * 60) def on_start(self): self.crawl('__START_URL__', callback=self.index_page) @config(age=10 * 24 * 60 * 60) def index_page(self, response): for each in response.doc('a[href^="http"]').items(): self.crawl(each.attr.href, callback=self.detail_page) @config(priority=2) def detail_page(self, response): return { "url": response.url, "title": response.doc('title').text(), }
crawl_config:爬蟲(chóng)的全局參數(shù)設(shè)置,例如請(qǐng)求頭和cookies可以在這里設(shè)置(傳入關(guān)鍵字及對(duì)應(yīng)的參數(shù)即可)
on_start(self):爬蟲(chóng)開(kāi)始爬取的入口
crawl:和requests有相同的功能 ,可以支持 get(默認(rèn)) 和 post,常用的參數(shù)有
data 是想要提交數(shù)據(jù)
callback 可以在執(zhí)行完 crawl后調(diào)用回調(diào)函數(shù)
method 是指定 訪(fǎng)問(wèn)方法
files 上傳文件,{'key': ('file.name': 'content')}
headers 請(qǐng)求頭,類(lèi)型dict
cookies 請(qǐng)求的 Cookies 類(lèi)型 dict
timeout 請(qǐng)求內(nèi)容里較大等待秒數(shù).默認(rèn)值:120
connect_timeout : 指定請(qǐng)求時(shí)鏈接超時(shí)時(shí)間,單位秒,默認(rèn)值:20
proxy : 可以設(shè)置代理服務(wù)器,暫時(shí)只支持http代理
感謝各位的閱讀!關(guān)于python爬蟲(chóng)中怎樣編寫(xiě)pyspider就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!