Scrapy:通用爬蟲CrawlSpider

爬取網站:http://example.python-scraping.com/

爬取字段:name  population

爬取環境:Ubuntu  python3.6

這個例子是學習通用爬蟲的案例,匹配規則經過我的改動,更加的直觀

主要代碼如下:

 rules = (
        Rule(LinkExtractor(allow=r'/places/default/index/', deny='/user'), follow=True),
        Rule(LinkExtractor(allow=r'view/', deny='/user'), callback='parse_item', follow=True)
    )

解析代碼:

item['name'] = response.xpath('//tr[@id="places_country_or_district__row"]//td[@class="w2p_fw"]/text()').extract()
        item['population'] = response.xpath('//tr[@id="places_population__row"]//td[@class="w2p_fw"]/text()').extract()

piplines保存數據:

    def process_item(self, item, spider):
        with open('info.txt', 'a', encoding='utf8')as f:
            f.write(str(item))
        return item

settings配置:去掉item pipline的註釋:

有些步驟省略了,可以參考的其他scrapy文檔

爬取記錄如下:

 爬取內容如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章