使用Scrapy爬取圖片入庫,並保存在本地


使用Scrapy爬取圖片入庫,並保存在本地

篇博客已經簡單的介紹了爬取數據流程,現在讓我們繼續學習scrapy

 

 

目標:

爬取愛卡汽車標題,價格以及圖片存入數據庫,並存圖到本地

 

好了不多說,讓我們實現下效果

 

我們仍用scrapy框架來編寫我們的項目:

 

1.首先用命令創建一個爬蟲項目(結合上篇博客),並到你的項目里如圖所示

 

 

2.先到你的settings.py中配置 ,這里需要注意要 爬圖(配置一個爬圖管道 ImagesPipeline 為系統中下載圖片的管道),

同時還有存圖地址(在項目中創建一個為images的文件夾),

存圖有多種方式,本人只是列舉其中一種,大家可采取不同的方法

 

 

3.然后打開你的爬蟲文件(即:car.py)開始編寫你要爬取的數據,這里需要注意,要將start_urls[] 改為我們要爬取的Url 地址,然后根據xpath爬取圖片 
(這里代碼得自己寫,不要復制)
 

 

 4.爬取的字段要跟   items.py里的一致

 

 

5.在命令行輸入啟動爬蟲命令 scrapy crawl car  運行就能看到爬到圖片存放在本地如下

6.最后入庫,看你要入那個庫,這里可入mysql和mongdb

 

mysql:  需提前創好庫以及表,表中字段

import pymysql
# class NewcarPipeline(object):
    # 連接mysql改為你的用戶密碼以及自己的庫
    # def __init__(self):
    #     self.conn = pymysql.connect(host='127.0.0.1',user='root', password='123456', db='zou')
        # 建立cursor對象
    #     self.cursor = self.conn.cursor()
    #
        # 傳值
    # def process_item(self, item, spider):
    #     name = item['name']
    #     content = item['content']
    #     price = item['price']
    #     image = item['image_urls']
    #
        # insert into 你的表名,括號里面是你的字段要一一對應
        
    #     sql = "insert into zou(name,content,price) values(%s,%s,%s)"
    #     self.cursor.execute(sql, (name,content,price))
    #     self.conn.commit()
    #     return item
    #關閉爬蟲
    # def close_spider(self, spider):
    #     self.conn.close()

 

mongdb:   不用提前建好庫,表

from pymongo import MongoClient
# class NewcarPipeline(object):
#     def open_spider(self, spider):
#         #     連端口 ip
#         self.con = MongoClient(host='127.0.0.1', port=27017)
#         #     庫
#         db = self.con['p1']
#         # 授權
#         self.con = db.authenticate(name='wumeng', password='123456', source='admin')
#         #     集合
#         self.coll = db[spider.name]

#     def process_item(self, item, spider):
#         # 添加數據
#         self.coll.insert_one(dict(item))
#         return item

#     def close_spider(self):
#         # 關閉
#         self.con.close()

 

7.運行 啟動爬蟲命令 scrapy crawl car 就可在庫中看到數據.

 

 

至此爬蟲項目做完了,這只是一個簡單的爬蟲,僅供參考,如遇其他方面的問題,可參考本人博客!盡情期待!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM