Scrapy學習筆記
目標
使用Scrapy爬蟲框架對獲取網站新聞數據。
爬蟲目標網站:http://tech.163.com
提取內容:
- url 新聞地址
- source 新聞來源
- title 新聞標題
- editor 新聞編輯
- time 新聞時間
- content 新聞正文內容
內容存儲方式:
- 文件
- 數據庫
代碼
- 爬蟲框架文件:
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 結構化內容提取方法實現