scrapy爬取資料並儲存到文字

2021-08-25 17:12:00 字數 1503 閱讀 7896

1.scrapy專案結構如下:

2.開啟spidler目錄下的duba.py檔案,**如下(這個是根據豆瓣一部分頁面獲取的熱門話題內容,有6條資料):

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

import scrapy

from scrapydemo.items import scrapydemoitem

from lxml import etree

class dubaspider(scrapy.spider):

name = 'duba'

allowed_domains = ['www.douban.com']

start_urls = ['']

def parse(self, response):

item = scrapydemoitem()

for each in response.xpath("//li[@class='rec_topics']"):

name = each.xpath("./a/@href").extract()

level = each.xpath("./a/text()").extract()

info = each.xpath("./span/text()").extract()

item['name']=name[0]

item['level'] = level[0]

item['info'] = info[0]

yield item

3.修改pipelines.py**如下:

import json

class scrapydemopipeline(object):

def __init__(self):

self.f = open("pipline.json",'a')

#pass

def process_item(self, item, spider):

content = json.dumps(dict(item),ensure_ascii = false,indent=2)+",\n"

self.f.write(content.encode("utf-8"))

return item

def close_spider(self,spider):

self.f.close()

4.在settings.py檔案中將下面**注釋去掉

item_pipelines =

然後在要生成檔案的目錄執行:scrapy crawl duba,就可以在當前目錄看到生成的檔案了。

當然,過程中遇到了一些問題,檢查後發現是空格,字元拼寫的毛病。尤其是在vim下,一定要注意先引入模組再呼叫,注意空格,字元拼寫等問題。接下來就是多多練習啦。

Scrapy爬取並儲存到TXT檔案

在建立完成專案並建立爬蟲的基礎上,編寫儲存到txt的專案 1.將 robotstxt obey 設定為false 2.將 item pipelines 開啟 item是scrapy提供的類似於字典型別的資料容器,它與字典最大的區別在於它規定了統一的資料規格樣式,即具有統一性與結構性。這樣既方便資料的...

Scrapy爬取網頁並儲存到資料庫中

scrapy爬取網頁並儲存到資料庫中 一.新建乙個scrapy工程。進入乙個你想用來儲存 的資料夾,然後執行 t scrapy startproject fjsen 會生成一堆資料夾和檔案 scrapy.cfg 專案配置檔案 tutorial 專案python模組,呆會 將從這裡匯入 tutoria...

scrapy 爬取資料儲存到資料庫

items.py coding utf 8 define here the models for your scraped items see documentation in import scrapy class mkwitem scrapy.item link scrapy.field typ...