python Scrapy框架原理解析
Python 爬蟲(chóng)包含兩個(gè)重要的部分:正則表達(dá)式和Scrapy框架的運(yùn)用, 正則表達(dá)式對(duì)于所有語(yǔ)言都是通用的,網(wǎng)絡(luò)上可以找到各種資源。
如下是手繪Scrapy框架原理圖,幫助理解
如下是一段運(yùn)用Scrapy創(chuàng)建的spider:使用了內(nèi)置的crawl模板,以利用Scrapy庫(kù)的CrawlSpider。相對(duì)于簡(jiǎn)單的爬取爬蟲(chóng)來(lái)說(shuō),Scrapy的CrawlSpider擁有一些網(wǎng)絡(luò)爬取時(shí)可用的特殊屬性和方法:
$ scrapy genspider country_or_district example.python-scrapying.com--template=crawl
運(yùn)行g(shù)enspider命令后,下面的代碼將會(huì)在example/spiders/country_or_district.py中自動(dòng)生成。
# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom example.items import CountryOrDistrictItemclass CountryOrDistrictSpider(CrawlSpider): name = ’country_or_district’ allowed_domains = [’example.python-scraping.com’] start_urls = [’http://example.python-scraping.com/’] rules = ( Rule(LinkExtractor(allow=r’/index/’, deny=r’/user/’), follow=True), Rule(LinkExtractor(allow=r’/view/’, deny=r’/user/’), callback=’parse_item’), ) def parse_item(self, response): item = CountryOrDistrictItem() name_css = ’tr#places_country_or_district__row td.w2p_fw::text’ item[’name’] = response.css(name_css).extract() pop_xpath = ’//tr[@id='places_population__row']/td[@class='w2p_fw']/text()’ item[’population’] = response.xpath(pop_xpath).extract() return item
爬蟲(chóng)類(lèi)包括的屬性:
name: 識(shí)別爬蟲(chóng)的字符串。 allowed_domains: 可以爬取的域名列表。如果沒(méi)有設(shè)置該屬性,則表示可以爬取任何域名。 start_urls: 爬蟲(chóng)起始URL列表。 rules: 該屬性為一個(gè)通過(guò)正則表達(dá)式定義的Rule對(duì)象元組,用于告知爬蟲(chóng)需要跟蹤哪些鏈接以及哪些鏈接包含抓取的有用內(nèi)容。以上就是python Scrapy框架原理解析的詳細(xì)內(nèi)容,更多關(guān)于Scrapy框架原理的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python sorted排序方法如何實(shí)現(xiàn)2. asp讀取xml文件和記數(shù)3. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題4. Python文本文件的合并操作方法代碼實(shí)例5. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車(chē)6. CSS自定義滾動(dòng)條樣式案例詳解7. PHP實(shí)現(xiàn)基本留言板功能原理與步驟詳解8. Python 中如何使用 virtualenv 管理虛擬環(huán)境9. python利用opencv實(shí)現(xiàn)顏色檢測(cè)10. 每日六道java新手入門(mén)面試題,通往自由的道路第二天
