通过python爬取的网页数据信息无法保存到MySQL,总显示保存失败是为什么呀,确实爬取到了但是保存不了
你在这代码下面把sql打印一下看看,具体生成了什么sql,然后复制去数据库执行一下,看看数据库有反应没,另外检查下数据库主键是否自增
将数据存储到MySQL里面,当然要首先要在数据库创建一张表的,然后表的结构根据自己的数据创建。
# -*- coding: utf-8 -*-
#@Project filename:PythonDemo SpiderJob.py
#@IDE :IntelliJ IDEA
#@Author :ganxiang
#@Date :2020/05/07 0007 10:18
#所需要的库
import requests
import parsel
import time
import pymysql
connection =pymysql.connect(host='127.0.0.1',
port=3306,
user='root',
password='1234567',
database='spider',
charset='utf8')
def create_table():
mycursor =connection.cursor()
#1,表存在则删除
mycursor.execute("DROP TABLE IF EXISTS job")
# 2,创建表
sql = """
create table job(
num int(11) NOT NULL AUTO_INCREMENT primary key,
company varchar(255) DEFAULT NULL,
positions varchar(255) DEFAULT NULL,
region varchar(255) DEFAULT NULL,
data_source varchar(255) DEFAULT NULL,
dates varchar(255) DEFAULT NULL
)
"""
try:
mycursor.execute(sql)
connection.commit()
print("创建表成功~")
except Exception as e:
print("创建失败~:{}".format(e))
finally:
mycursor.close()
# connection.close() #创建表完成关闭连接,这里后面还用到就将其注释掉,如果只用来创建表创建完成可以开启关闭连接
问题分析: 根据提供的参考资料,可以看出在爬取数据成功后,是通过使用pymysql库连接到MySQL数据库进行数据存储的。因此,保存失败的原因可能是数据库连接出错或者存储的数据格式有误。
解决方案: 1. 确保正确安装了pymysql库,可以在Python环境中使用import pymysql
来检查是否安装成功。
import pymysql
try:
connection = pymysql.connect(host='127.0.0.1',
port=3306,
user='root',
password='1234567',
database='spider',
charset='utf8')
print("连接成功!")
except Exception as e:
print("连接失败:", str(e))
def create_table():
mycursor = connection.cursor()
# 1. 表存在则删除
mycursor.execute("DROP TABLE IF EXISTS job")
# 2. 创建表的SQL语句
sql = """
CREATE TABLE job(
num INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
company VARCHAR(255) DEFAULT NULL,
positions VARCHAR(255) DEFAULT NULL,
region VARCHAR(255) DEFAULT NULL,
data_source VARCHAR(255) DEFAULT NULL,
dates VARCHAR(255) DEFAULT NULL
)
"""
try:
mycursor.execute(sql)
connection.commit()
print("创建表成功!")
except Exception as e:
print("创建失败:", str(e))
finally:
mycursor.close()
确保爬取到的数据以正确的格式存入到一个列表中,如上文提供的参考资料中的infoList
列表。请注意数据的顺序和类型要与表结构中的字段一致。
将爬取到的数据插入到表中,可以使用executemany()
方法批量插入数据。示例代码如下:
def save_data(data_list):
mycursor = connection.cursor()
sql = """
INSERT INTO job (company, positions, region, data_source, dates)
VALUES (%s, %s, %s, %s, %s)
"""
try:
mycursor.executemany(sql, data_list)
connection.commit()
print("数据保存成功!")
except Exception as e:
print("保存失败:", str(e))
finally:
mycursor.close()
以上就是可能导致保存失败的原因和相应的解决方案,根据以上步骤检查和调试,可以帮助你解决保存数据到MySQL数据库失败的问题。
检查数据库有没有连上,表结构(必选字段,类型),主键是否重复,插入的数据里是否有特殊符号,比如说单引号,导致sql拼接后失败