使用Scrapy對新聞進行爬蟲(零)

Scrapy學習筆記

目標

使用Scrapy爬蟲框架對獲取網站新聞數據。

爬蟲目標網站:http://tech.163.com

提取內容:

  1. url 新聞地址
  2. source 新聞來源
  3. title 新聞標題
  4. editor 新聞編輯
  5. time 新聞時間
  6. content 新聞正文內容

內容存儲方式:

  1. 文件
  2. 數據庫

代碼

  1. 爬蟲框架文件:
scrapy startproject NewsSpiderMan  // 創建代碼

結果:
├── NewsSpiderMan
│ ├── DmozSpider // 自建目錄,存放針對DOMZ網站的爬蟲類
│ │ ├── init.py
│ │ └── dmoz_spider.py
│ ├── NewsSpider // 自建目錄,存放針對新聞的爬蟲類
│ │ ├── NewsSpider.py
│ │ ├── NewsSpider.pyc
│ │ ├── init.py
│ │ └── init.pyc
│ ├── init.py
│ ├── init.pyc
│ ├── items.py // 爬蟲提取內容設定
│ ├── items.pyc
│ ├── pipelines.py // 爬到數據後使用ITEM PIPELINE過濾處理數據並存放
│ ├── pipelines.pyc
│ ├── settings.py // 爬蟲框架下配置
│ └── settings.pyc
├── README.md
├── news.txt // 爬蟲結果
└── scrapy.cfg

GITHUB: https://github.com/chenxilinsidney/ScrapyNews

運行方式:scrapy crawl news163spider

爬蟲類

#!/usr/bin/env python
# -*-encoding:UTF-8-*-

from NewsSpiderMan.items import NewsItem
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class NewsSpider(CrawlSpider):
    name = "news163spider"
    allowed_domains = ["tech.163.com"]
    start_urls = ["http://tech.163.com"]

    rules = [
        Rule(LinkExtractor(allow='tech.163.com/16/.*\.html'),
             follow=True, callback='parse_item')
    ]

    def parse_item(self, response):
        item = NewsItem()
        item['url'] = [response.url]
        item['source'] =\
            response.xpath('//a[@id="ne_article_source"]/text()').\
            extract()
        item['title'] =\
            response.xpath('//div[@class="post_content_main"]/h1/text()').\
            extract()
        item['editor'] =\
            response.xpath('//span[@class="ep-editor"]/text()').\
            extract()
        item['time'] =\
            response.xpath('//div[@class="post_time_source"]/text()').\
            extract()
        item['content'] =\
            response.xpath('//div[@class="post_text"]/p/text()').\
            extract()
        for key in item:
            for data in item[key]:
                self.logger.debug("item %s value %s" % (key, data))
        return item

    # def parse_start_url(self, response):
    #    log.start()
    #    log.msg(str(response.xpath('//a/@href')))
    #    return response.xpath('//a/@href')

關鍵點:
1. name 標識一個爬蟲,框架調用時使用(如命令:scrapy crawl news163spider)
2. start_urls 初始爬蟲目標網站
3. Rule 爬蟲規則
4. parse_item 結構化內容提取方法實現

結果

新聞數據舉例

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