python3利用Scrapy實現爬蟲--學習筆記
阿新 • • 發佈:2019-01-31
目的:需要從網頁上爬去一些資訊
工具:Python scrapy
爬去CSDN中部落格的閱讀排行
第一步:
建立scrapy專案 scrapy startproject XXX
第二步:
建立爬蟲 進入專案目錄 執行 scrapy genspider csdn_spider csdn.net
此時的專案結構為
第三步:
編輯 csdn/item.py 定義我們需要爬取的欄位
這裡我們爬取 閱讀排行前十名的 文章標題和閱讀次數
name 為文章標題
total 為閱讀數量
import scrapy class CsdnItem(scrapy.Item): # define the fields for your item here like:name = scrapy.Field() total = scrapy.Field()
第四部:
編輯爬蟲檔案 csdn/spiders/csdn_spider.py
import scrapy from csdn.items import CsdnItem class CsdnSpiderSpider(scrapy.Spider): name = 'csdn_spider' allowed_domains = ['csdn.net'] start_urls = ['https://blog.csdn.net/wuchenlhy'] def parse(self, response): body = response.xpath('//*[@id="hotarticls"]/ul[2]/li') for value in body: title = value.xpath('./a/@title').extract()[0] total = value.xpath('./span/text()').extract()[0] print(title, total) item = CsdnItem() item['name'] = title item['total'] = total yield item
第五步:
儲存我們爬取到的內容
編輯csdn/settings.py
找到這一段程式碼取消掉註釋
# Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'csdn.pipelines.CsdnPipeline': 300, #}
變成這個樣子
# Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'csdn.pipelines.CsdnPipeline': 300, }
之後編輯csdn/pipelines.py
class CsdnPipeline(object): def process_item(self, item, spider): with open('csdn.txt', 'a') as fp: fp.write('{0} {1}\n'.format(item['name'], item['total']))
爬蟲程式碼完畢
最後一步:執行爬蟲
scrapy crawl csdn_spider --nolog
抓取內容我們儲存在專案根目錄的 csdn.txt中