Writing items to a MySQL database in Scrapy

后端 未结 3 657
囚心锁ツ
囚心锁ツ 2020-12-02 08:48

I am new to Scrapy, I had the spider code

class Example_spider(BaseSpider):
   name = \"example\"
   allowed_domains = [\"www.example.com\"]

   def start_re         


        
3条回答
  •  一生所求
    2020-12-02 09:15

    Try the following code in your pipeline

    import sys
    import MySQLdb
    import hashlib
    from scrapy.exceptions import DropItem
    from scrapy.http import Request
    
    class MySQLStorePipeline(object):
        def __init__(self):
            self.conn = MySQLdb.connect('host', 'user', 'passwd', 
                                        'dbname', charset="utf8",
                                        use_unicode=True)
            self.cursor = self.conn.cursor()
    
        def process_item(self, item, spider):    
            try:
                self.cursor.execute("""INSERT INTO example_book_store (book_name, price)  
                            VALUES (%s, %s)""", 
                           (item['book_name'].encode('utf-8'), 
                            item['price'].encode('utf-8')))            
                self.conn.commit()            
            except MySQLdb.Error, e:
                print "Error %d: %s" % (e.args[0], e.args[1])
            return item
    

提交回复
热议问题