溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

scrapy數(shù)據(jù)存儲(chǔ)在mysql數(shù)據(jù)庫(kù)的兩種方式(同步和異步)

發(fā)布時(shí)間:2020-10-19 14:38:24 來(lái)源:腳本之家 閱讀:373 作者:俠客云 欄目:開(kāi)發(fā)技術(shù)

方法一:同步操作

1.pipelines.py文件(處理數(shù)據(jù)的python文件)

import pymysql
 
class LvyouPipeline(object):
  def __init__(self):
    # connection database
    self.connect = pymysql.connect(host='XXX', user='root', passwd='XXX', db='scrapy_test') # 后面三個(gè)依次是數(shù)據(jù)庫(kù)連接名、數(shù)據(jù)庫(kù)密碼、數(shù)據(jù)庫(kù)名稱(chēng)
    # get cursor
    self.cursor = self.connect.cursor()
    print("連接數(shù)據(jù)庫(kù)成功")
 
  def process_item(self, item, spider):
    # sql語(yǔ)句
    insert_sql = """
    insert into lvyou(name1, address, grade, score, price) VALUES (%s,%s,%s,%s,%s)
    """
    # 執(zhí)行插入數(shù)據(jù)到數(shù)據(jù)庫(kù)操作
    self.cursor.execute(insert_sql, (item['Name'], item['Address'], item['Grade'], item['Score'],
                     item['Price']))
    # 提交,不進(jìn)行提交無(wú)法保存到數(shù)據(jù)庫(kù)
    self.connect.commit()
 
  def close_spider(self, spider):
    # 關(guān)閉游標(biāo)和連接
    self.cursor.close()
    self.connect.close()

2.配置文件中

scrapy數(shù)據(jù)存儲(chǔ)在mysql數(shù)據(jù)庫(kù)的兩種方式(同步和異步)

方式二 異步儲(chǔ)存

pipelines.py文件:

通過(guò)twisted實(shí)現(xiàn)數(shù)據(jù)庫(kù)異步插入,twisted模塊提供了 twisted.enterprise.adbapi

  1. 導(dǎo)入adbapi

  2. 生成數(shù)據(jù)庫(kù)連接池

  3. 執(zhí)行數(shù)據(jù)數(shù)據(jù)庫(kù)插入操作

  4. 打印錯(cuò)誤信息,并排錯(cuò) 

import pymysql
from twisted.enterprise import adbapi
# 異步更新操作
class LvyouPipeline(object):
  def __init__(self, dbpool):
    self.dbpool = dbpool
 
  @classmethod
  def from_settings(cls, settings): # 函數(shù)名固定,會(huì)被scrapy調(diào)用,直接可用settings的值
    """
    數(shù)據(jù)庫(kù)建立連接
    :param settings: 配置參數(shù)
    :return: 實(shí)例化參數(shù)
    """
    adbparams = dict(
      host=settings['MYSQL_HOST'],
      db=settings['MYSQL_DBNAME'],
      user=settings['MYSQL_USER'],
      password=settings['MYSQL_PASSWORD'],
      cursorclass=pymysql.cursors.DictCursor  # 指定cursor類(lèi)型
    )
 
    # 連接數(shù)據(jù)池ConnectionPool,使用pymysql或者M(jìn)ysqldb連接
    dbpool = adbapi.ConnectionPool('pymysql', **adbparams)
    # 返回實(shí)例化參數(shù)
    return cls(dbpool)
 
  def process_item(self, item, spider):
    """
    使用twisted將MySQL插入變成異步執(zhí)行。通過(guò)連接池執(zhí)行具體的sql操作,返回一個(gè)對(duì)象
    """
    query = self.dbpool.runInteraction(self.do_insert, item) # 指定操作方法和操作數(shù)據(jù)
    # 添加異常處理
    query.addCallback(self.handle_error) # 處理異常
 
  def do_insert(self, cursor, item):
    # 對(duì)數(shù)據(jù)庫(kù)進(jìn)行插入操作,并不需要commit,twisted會(huì)自動(dòng)commit
    insert_sql = """
    insert into lvyou(name1, address, grade, score, price) VALUES (%s,%s,%s,%s,%s)
    """
    self.cursor.execute(insert_sql, (item['Name'], item['Address'], item['Grade'], item['Score'],
                         item['Price']))
 
  def handle_error(self, failure):
    if failure:
      # 打印錯(cuò)誤信息
      print(failure)

注意:

1、python 3.x 不再支持MySQLdb,它在py3的替代品是: import pymysql。

2、報(bào)錯(cuò)pymysql.err.ProgrammingError: (1064, ……

原因:當(dāng)item['quotes']里面含有引號(hào)時(shí),可能會(huì)報(bào)上述錯(cuò)誤

解決辦法:使用pymysql.escape_string()方法

例如:

sql = """INSERT INTO video_info(video_id, title) VALUES("%s","%s")""" % (video_info["id"],pymysql.escape_string(video_info["title"]))

3、存在中文的時(shí)候,連接需要添加charset='utf8',否則中文顯示亂碼。

4、每執(zhí)行一次爬蟲(chóng),就會(huì)將數(shù)據(jù)追加到數(shù)據(jù)庫(kù)中,如果多次的測(cè)試爬蟲(chóng),就會(huì)導(dǎo)致相同的數(shù)據(jù)不斷累積,怎么實(shí)現(xiàn)增量爬???

  • scrapy-deltafetch
  • scrapy-crawl-once(與1不同的是存儲(chǔ)的數(shù)據(jù)庫(kù)不同)
  • scrapy-redis
  • scrapy-redis-bloomfilter(3的增強(qiáng)版,存儲(chǔ)更多的url,查詢(xún)更快)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI