Python 爬蟲包含兩個重要的部分:正則表達式和Scrapy框架的運用, 正則表達式對於全部語言都是通用的,網絡上能夠找到各類資源。css
以下是手繪Scrapy框架原理圖,幫助理解html
以下是一段運用Scrapy建立的spider:使用了內置的crawl模板,以利用Scrapy庫的CrawlSpider。相對於簡單的爬取爬蟲來講,Scrapy的CrawlSpider擁有一些網絡爬取時可用的特殊屬性和方法:python
$ scrapy genspider country_or_district example.python-scrapying.com--template=crawl正則表達式
運行genspider命令後,下面的代碼將會在example/spiders/country_or_district.py中自動生成。
api
1 # -*- coding: utf-8 -*- 2 import scrapy 3 from scrapy.linkextractors import LinkExtractor 4 from scrapy.spiders import CrawlSpider, Rule 5 from example.items import CountryOrDistrictItem 6 7 8 class CountryOrDistrictSpider(CrawlSpider): 9 name = 'country_or_district' 10 allowed_domains = ['example.python-scraping.com'] 11 start_urls = ['http://example.python-scraping.com/'] 12 13 rules = ( 14 Rule(LinkExtractor(allow=r'/index/', deny=r'/user/'), 15 follow=True), 16 Rule(LinkExtractor(allow=r'/view/', deny=r'/user/'), 17 callback='parse_item'), 18 ) 19 20 def parse_item(self, response): 21 item = CountryOrDistrictItem() 22 name_css = 'tr#places_country_or_district__row td.w2p_fw::text' 23 item['name'] = response.css(name_css).extract() 24 pop_xpath = '//tr[@id="places_population__row"]/td[@class="w2p_fw"]/text()' 25 item['population'] = response.xpath(pop_xpath).extract() 26 return item
爬蟲類包括的屬性:網絡