Search code examples
pythonmysqlpython-3.xscrapyscrapy-pipeline

Scrapy-MySQL pipeline does not save data


I'm scraping a website for its external links using scrapy and storing those links to MYSQl db. i used a snippet in my code. when i run spider i see the links being scrapped but gives error

2018-03-07 13:33:27 [scrapy.log] ERROR: not all arguments converted during string formatting

It is clear that links are not being converted to string due to the dots,slashes, commas and dash. So how can i pass the links and store them without error.TIA

pipeline.py

from scrapy import log
from twisted.enterprise import adbapi
import MySQLdb.cursors


class MySQLStorePipeline(object):

def __init__(self):
    self.dbpool = adbapi.ConnectionPool('MySQLdb', db='usalogic_testdb',
            user='root', passwd='1234', cursorclass=MySQLdb.cursors.DictCursor,
            charset='utf8', use_unicode=True)

def process_item(self, item, spider):
    # run db query in thread pool
    query = self.dbpool.runInteraction(self._conditional_insert, item)
    query.addErrback(self.handle_error)

    return item

def _conditional_insert(self, tx, item):
    # create record if doesn't exist. 
    # all this block run on it's own thread
    tx.execute("select * from test where link = %s", (item['link'], ))
    result = tx.fetchone()
    if result:
        log.msg("Item already stored in db: %s" % item, level=log.DEBUG)
    else:
        tx.execute(\
            "insert into test (link) "
            "values (%s)",
            (item['link'])
        )
        log.msg("Item stored in db: %s" % item, level=log.DEBUG)

def handle_error(self, e):
    log.err(e)

When when given run command the ITEMS.py

class CollectUrlItem(scrapy.Item):
link = scrapy.Field()

settings.py

ITEM_PIPELINES = {

'rvca4.pipelines.MySQLStorePipeline': 800,
}

Solution

  • I think if you use a list instead of a tuple, it will work

    tx.execute(\
            "insert into test (link) "
            "values (%s)",
            [ item['link'] ]
        )
    

    OR, add a comma to tuple

    tx.execute(\
            "insert into test (link) "
            "values (%s)",
            (item['link'], )
        )
    

    Because adding a trailing comma in a tuple is what actually makes it a tuple. Read below

    (1)  # the number 1 (the parentheses are wrapping the expression `1`)
    (1,) # a 1-tuple holding a number 1