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

2021-07-22 04:56:55 字數 1928 閱讀 1135

scrapy框架下的item用於定義抓取的資料內容。實現從非結構化資料(網頁)中提取結構化資料時,結構化資料所用的資料結構即為該item(scrapy.item)

宣告乙個item類,scrapy匯入該模組並使用item例項來儲存結構化資料。

所有資料的型別field實際是乙個dict的別名而已。

開發者建立item類只需關注一點:1.需要從**中抓取哪些資料(採用變數名標誌)。

1.檔案:items.py

# -*- coding: utf-8 -*-

# define here the models for your scraped items

## see documentation in:

# import scrapy

class

dmozitem

(scrapy.item):

""" define the fields for your item here like.

for crawl dmoz items

"""title = scrapy.field()

link = scrapy.field()

desc = scrapy.field()

class

newsitem

(scrapy.item):

""" define the fields for news

for crawl news items

"""url = scrapy.field()

source = scrapy.field()

title = scrapy.field()

editor = scrapy.field()

time = scrapy.field()

content = scrapy.field()

2.抓取spider模組匯入item類並使用

from newsspiderman.items import newsitem
使用到的**片段:

class

newsspider

(crawlspider):

defparse_news

(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]:

log.msg("item %s value %s" % (key, data))

return item

擁用更加靈活、高效的api來讓spider模組對item進行資料填充,更好的對**資料的解析並填入item項。

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

item pipeline 主要用於從網頁抓取 spider 後對資料item進行收集,寫入資料庫或檔案中。spider 在獲得item後,會傳遞給item pipeline,進行後續資料收集工作。在setting中對item pipeline類路徑進行配置,scrapy框架會呼叫該item pip...

網路爬蟲(四) 使用Scrapy爬取網易新聞

import scrapy class newsitem scrapy.item news thread scrapy.field news title scrapy.field news url scrapy.field news time scrapy.field news source scr...

利用scrapy框架進行爬蟲

1.安裝2.用scrapy爬蟲四步走 第一步 編寫items.py 第二步 編寫spiders下的 py 檔案 第三步 編寫pipelines.py檔案 第四步 開啟settings.py 檔案更改配置 3.基於scrapy爬蟲框架,只需在命令列中輸入 scrapy startproject 命令,...