簡體   English   中英

無法使用Python和scrapy管道將數據插入MySQL

[英]Unable to insert data to MySQL using Python and scrapy pipelines

我已經嘗試了數小時來解決此問題,但仍然無法使其正常工作。 我正在使用scrapy從網站上抓取數據,然后嘗試將其插入MySQL數據庫。 這是我的數據庫代碼:

import MySQLdb


class Database:

host = 'localhost'
user = 'root'
password = 'test123'
db = 'scraping_db'

def __init__(self):
    self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db,use_unicode=True, charset="utf8")
    self.cursor = self.connection.cursor()

def insert(self, query,params):
    try:
        self.cursor.execute(query,params)
        self.connection.commit()
    except Exception as ex:
        self.connection.rollback()


def __del__(self):
    self.connection.close()

這是我進行插入查詢並傳遞給上述類的insert方法的管道代碼:

from con import Database


class LinkPipeline(object):

    def __init__(self):
        self.db=Database()

    def process_item(self, item, spider):
        query="""INSERT INTO links (title, location,company_name,posted_date,status,company_id,scraped_link,content,detail_link,job_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s)"""
        params=(item['title'], item['location'], item['company_name'], item['posted_date'], item['status'], item['company_id'], item['scraped_link'], item['content'], item['detail_link'],item['job_id'])
        self.db.insert(query,params)
        return item

這在我的本地計算機上完全可以正常工作。 但是在服務器上,我得到以下錯誤:

1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \')

當我打印參數並從異常塊查詢時,我有以下內容:

查詢變量:

INSERT INTO links (title, location,company_name,posted_date,status,company_id,scraped_link,content,detail_link,job_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s)

參數變量:

((u'Account Leader, Sr',), (u'Sydney',), (u'\n    Halliburton',), (datetime.datetime(2018, 4, 9, 21, 55, 46, 789575),), ('Pending',), ([u'0e4554ac6dcff427'],), (u'https://www.site.com.au/rc/clk?jk=3f41218887882940&fccid=0e4554ac6dcff427&vjs=3',), 'Job Content', 'https://jobs.halliburton.com/job/Account-Leader%2C-Sr-IS/437741300/?feedId=162400', ([u'3f41218887882940'],))

我覺得元組數據是MySQL字符串由於引號破損的元凶。 但是我對Python很陌生,我不確定我是否在SO上簽了另一個問題以遵循此語法插入MySQL數據庫,即:

self.db.insert(query,params)

上面的代碼在我的本地計算機上工作正常,但在服務器上失敗。 請指引我正確的方向。 非常感謝你!

看起來元組封裝是您的問題。 輸出是什么:

print( repr( item['location'] ))

那就是“打印item ['location']的(編碼器)表示形式”(而不是試圖對打印聰明一些。

>>> print( repr( item['location'] ))
('Sydney',)     # A tuple, 1-long, containing a string

>>> print( repr( item['location'] ))
'Sydney'        # A string

如果是第一個,那么您在item內傳遞的數據結構顯然具有額外的封裝層,您的代碼無法為其解釋。 快速而骯臟的方法來使您正常運行:

def process_item(self, item, spider):
    query="""INSERT INTO links (title, location,company_name,posted_date,status,company_id,scraped_link,content,detail_link,job_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s)"""
    params=(item['title'][0], item['location'][0], ...
    self.db.insert(query,params)
    return item

請注意,這並不是一個可靠的API解決方案:如果這些嵌入式元組之一的長度為零,會發生什么? (提示:異常)。 我也沒有填寫其余部分,因為看起來您的item中有些元素根本沒有被封裝,而另一些元素則被雙重封裝了。

此外,此后您的數據可能會出現一些編碼錯誤,因為某些元素是unicode,而其他元素則不是。 例如:

(u'Sydney',)  ...    ('Pending',)

您可能要檢查一下您的架構需要什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM