python - scrapy mysql 返回空结果

标签 python mysql scrapy scrapy-pipeline

所以我的问题是抓取的信息不会显示在数据库中。

我的蜘蛛可以很好地打印信息,例如在 .json 文件中。

管道.py

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="10.0.2.2", user='root', passwd='', db='mpmf', charset="utf8", use_unicode=True)
   self.cursor = self.conn.cursor()

def process_item(self, item, stack):    
    try:
        self.cursor.execute("""INSERT INTO test (pen, name)  
                    VALUES (%s, %s)""", 
                   (item['pen'].encode('utf-8'), item['name'].encode('utf-8')))

    self.conn.commit()


except MySQLdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])


return item

并在settings.py中我添加了

ITEM_PIPELINES = {
'stack.pipelines.MySQLStorePipeline': 300,
}

我的日志显示此错误,但您仍然可以看到信息收集工作正常,即使它显示此错误。

 File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line   577, in _runCallbacks
 current.result = callback(current.result, *args, **kw)
 File "/root/stack/stack/pipelines.py", line 14, in process_item
 self.cursor.execute("""INSERT INTO test (pen, name) VALUES (%s, %s)""",  (item['pen'].encode('utf-8'), item['name'].encode('utf-8')))
 AttributeError: 'list' object has no attribute 'encode'

因此没有结果导入数据库

最佳答案

解决了 问题是缩进和列表对象没有属性

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="10.0.2.2", user='root', passwd='', db='mpmf', charset="utf8", use_unicode=True)
self.cursor = self.conn.cursor()

def process_item(self, item, stack):    
try:
    self.cursor.execute("""INSERT INTO test (pen, name) VALUES (%s, %s)""", (item['pen'][0].encode('utf-8'), item['name'][0].encode('utf-8')))

    self.conn.commit()


except MySQLdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])


return item

关于python - scrapy mysql 返回空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38814777/

相关文章:

Python 多索引函数,在分割列中保留顺序或其他可能的解决方案

python - 如何在 __init__ 中使用 await 设置类属性

php - mysqli有时查询不到结果

javascript - 使用 PHP 和 AJAX 的 Mysql UPDATE,无法更新数据库

python - Macbook 上的 scrapy 错误 : Module 'tutorial' already exists

url - Scrapy:遵循具有特定规则的 URL

python - 让两个python脚本相互对话的最简单方法?

Python .loc 困惑

php - 运行 sql 查询以插入到表中并更新另一个表

python - 使用 Scrapy shell 抓取 JSON 文件时终端窗口自动关闭