请教个爬 虫存 mysql 的问题

2020-05-07 21:46:21 +08:00
 Colorful

import pymongo

from pymongo import MongoClient

import pymysql as pq

class Pipeline(object): def init(self): self.conn = pq.connect(host='127.0.0.1', user='root',port='3306', passwd='123456', db='root', charset='utf8') self.cur = self.conn.cursor() # def init(self): # host = '127.0.0.1' # port = 27017 # client = pymongo.MongoClient(host=host,port=port) # collection = client.local.letsgojpt # self.post = collection

def process_item(self, item, spider):
    for i in range(0,len(item["title_all"])):
        # sql = "insert into letsgojp(title_all, center_all) VALUES (%s, %s)"
        self.cur.execute("insert into letsgojp(title_all,center_all) values(%s,%s)",(item['title_all'][i],item['center_all'][i]))
        self.conn.commit()
        # self.post.insert(data)
    return item

def close_spider(self, spider):
    self.cur.close()
    self.conn.close()

主要是这行报错

self.cur.execute("insert into letsgojp(title_all,center_all) values(%s,%s)",(item['title_all'][i],item['center_all'][i]))

用 mongo 的时候是正常存数据的,但是用 mysql 就报错,网上找一些,不太会用,请教各位大神了

2311 次点击
所在节点    Python
14 条回复
ClericPy
2020-05-07 21:56:44 +08:00
1. 找个贴代码的地方把缩进留下...

2. 报错信息解释 90% 问题, 大部分时间报错信息最后一行一搜 stackoverflow 上都有同行遇到过

3. 纯看的话, 实在猜不到啊... 就语法来说, pymysql 会自动转义, 问题不大, 看你的列名也没有敏感关键字所以不加反引号也没事
jugelizi
2020-05-07 22:00:52 +08:00
[item['title_all'][i],item['center_all'][i]] 是不是?
也有可能没处理好特殊字符 错误提示贴下啊
Colorful
2020-05-07 22:17:51 +08:00
@jugelizi 应该不会的吧,因为存 mongo 的时候是没总是的
chaneyccy
2020-05-07 22:55:09 +08:00
不贴报错信息,这也看不出来哪里有问题吧

没用过 SQL 好奇搜了一圈,没有发现模块导入是 import pymysql as pq,问题在这?
Colorful
2020-05-07 23:05:28 +08:00
@chaneyccy 不是那里,能爬到一条数据
self.cur.execute("insert into letsgojp(title_all,center_all) values(%s,%s)",(item['title_all'][i],item['center_all'][i]))

主要就是这行
aydd2004
2020-05-07 23:17:58 +08:00
execute 的内容 print 出来看一下

实在不行粘到 mysql 里面执行一下
dorothyREN
2020-05-08 00:01:50 +08:00
占位符那里的问题,插入字符串 需要 加上 \'%s\'
dorothyREN
2020-05-08 00:06:12 +08:00
@dorothyREN #7 ``` def save_data(self, title, content):
sql = "INSERT INTO test(title,content) VALUES (\'%s\',\'%s\')" % (title, content)
# print(sql)
self.cur.execute(sql)
self.conn.commit()
```
crella
2020-05-08 07:24:08 +08:00
mysql 新版的 mb-utf8 编码设置有点麻烦。

建议直接 postgresql
triangle111
2020-05-08 08:51:33 +08:00
print 一下 sql 语句到 mysql 执行就知道错哪了, 应该是字符串没有引号导致的吧
annielong
2020-05-08 09:20:56 +08:00
一般都是编码和非法字符的问题,打印 sql 语句就可以看出来
zhangysh1995
2020-05-08 13:58:46 +08:00
添加 try except,抓 mysql.connector.errors.DatabaseError 错误
leapV3
2020-05-08 15:04:30 +08:00
你试试将表名与列名加上反引号
AmberJiang
2020-05-08 16:19:26 +08:00
感觉像是 insert 语句那里存在语法错误。。。贴报错图出来看看吧

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/669438

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX