python - 用scrpay写爬虫,同样的代码-o保存成CSV时一切正常,但同时写入Mysql数据库时很多数据重复且不齐全
黄舟
黄舟 2017-04-17 17:46:21
[Python讨论组]

用scrpay写爬虫用大众点评练手,同样的代码-o保存成CSV时一切正常,但同时写入Mysql数据库时很多数据重复且不齐全。

csv文件一切正常。

Mysql里面的数据库一塌糊涂。

同一段代码,完全没有头绪,请高手帮忙。

class MySQLStorePipeline(object):
    """docstring for MySQLstor"""
    def __init__(self):
 
        self.dbpool = adbapi.ConnectionPool('MySQLdb',
            host = 'localhost',
            db = 'dianping',
            user = 'root',
            passwd = 'root',
            cursorclass = MySQLdb.cursors.DictCursor,
            charset = 'utf8',
            use_unicode = True
        )
    def process_item(self, item, spider):
        #print 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):
        if item.get('user_id'):
         
            tx.execute(\
                "insert into testtable_gz (city, store_name, store_id, book, group_buy, branch, average_spend, style, store_area, store_addr, store_url, comment_url, store_phone, user_id, star, taste, environment, service, comment, comment_date, user_url)\
                values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
 
                (item['city'],
                 item['store_name'],
                 item['store_id'],
                 item['book'],
                 item['group_buy'],
                 item['branch'],
                 item['average_spend'],
                 item['style'],
                 item['store_area'],
                 item['store_addr'],
                 item['store_url'],
                 item['comment_url'],
                 item['store_phone'],
                 item['user_id'], 
                 item['star'], 
                 item['taste'],
                 item['environment'],
                 item['service'],
                 item['comment'],
                 item['comment_date'],
                 item['user_url']
                ))
 
    def handle_error(self, e):
        log.err(e)
        

这是Pinelines.py代码。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(3)
巴扎黑

请问下,我写入csv都是乱码,你这个中文怎么都是正确的?

黄舟

笨方法,pipeline里面不连接MySQL,而是自己生成sql插入语句保存到文件。最后爬完后直接就复制语句去执行。上次遇到你这个问题我就是这么干的

PHP中文网

因为数据库柄插入操作是次线程的,与主线程不同步,但是你传递给数据库柄的item 是引用传递,如果主线程中改变item的值了,那么次线程中的item也会改变,所以当数据库真正要插入第一条记录时,可能已经成了第三条记录了。前面两条记录就没有了。解决办法:将引用传递 修改成值传递,或者 生成多个item对象,每次yeild的item对象不是同一个。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号