需要引入包
import pymssql
数据库是微软的SQL server
新增两个函数:
第一个创建表,此方法只需要运行一次,第二次可以注释 create_table(),在文章末尾查看
数据库名字是guijinshu,先提前手动建库,这里本来想写进去但是报了一个 SQL Server不允许在多语句事务中使用,于是作罢
def create_table():
conn = pymssql.connect(server='127.0.0.1', user='sa', password='root', database='guijinshu')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE gold_quote (
id INT IDENTITY(1,1) PRIMARY KEY,
showCode NVARCHAR(50),
name NVARCHAR(50),
price DECIMAL(10, 2),
unit NVARCHAR(50),
sellPrice DECIMAL(10, 2),
buyPrice DECIMAL(10, 2),
updownPercent DECIMAL(10, 2),
updown DECIMAL(10, 2),
openPrice DECIMAL(10, 2),
highPrice DECIMAL(10, 2),
lowPrice DECIMAL(10, 2),
closePrice DECIMAL(10, 2),
time DATETIME
)
''')
conn.commit()
conn.close()
第二个是数据插入表的方法,也是比较简单
def insert_data(showCode, name, price, unit, sellPrice, buyPrice, updownPercent, updown, openPrice, highPrice, lowPrice, closePrice, time):
conn = pymssql.connect(server='127.0.0.1', user='sa', password='root', database='guijinshu')
cursor = conn.cursor()
cursor.execute('''
INSERT INTO gold_quote (showCode, name, price, unit, sellPrice, buyPrice, updownPercent, updown, openPrice, highPrice, lowPrice, closePrice, time)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
''', (showCode, name, price, unit, sellPrice, buyPrice, updownPercent, updown, openPrice, highPrice, lowPrice, closePrice, time))
conn.commit()
conn.close()
注意把日期时间的部分改为 日期时间 的格式去掉年月日
formatted_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
这次继续优化,将‘None’全部改为None
新增一个 商品中文名
# 商品中文名
showname = None
后面给他赋值一下,并在末尾调用插入数据到数据库的方法insert_data()插入
if q63Val == 0:
q63Val = None
q70Val = None
q80Val = None
print("代码 showCode: " + showCode)
if showCode in gold_dict:
showname = gold_dict[showCode]
print("名称:"+showname)
print("价格 price: " + q63Val)
print("单位 unit: " + unit)
print("卖出价 sellPrice: " + q6Val)
print("买入价 buyPrice: " + q5Val)
print("涨跌幅百分比 updownPercent: " + q70Val)
print("涨跌幅 updown: " + q80Val)
print("开盘价 open: " + q1Val)
print("最高价 high: " + q3Val)
print("最低价 low: " + q4Val)
print("收盘价 close: " + q2Val)
print("时间 time: " + str(formatted_time))
print("\n")
insert_data(showCode, showname, q63Val, unit, q6Val, q5Val, q70Val, q80Val, q1Val, q3Val, q4Val, q2Val, formatted_time)
在此处增加create_table(),第一次运行时使用,运行完毕后注释掉
# create_table()
get_quote()
运行结果:
最后脚本可以保存在服务器,使用定时任务策略 编写定时运行Python脚本,从而定时爬取数据到数据库