鱼C论坛

 找回密码
 立即注册
查看: 2328|回复: 4

[已解决]请高手帮我看看代码的错在哪里,谢谢。

[复制链接]
发表于 2022-7-20 21:42:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#导入需要使用到的模块
import urllib
import re
import pandas as pd
import pymysql
import os

#爬虫抓取网页函数
def getHtml(url):
    html = urllib.request.urlopen(url).read()
    html = html.decode('gbk')
    return html

#抓取网页股票代码函数
def getStackCode(html):
    s = r'<li><a target="_blank" href="http://quote.eastmoney.com/\S\S(.*?).html">'
    pat = re.compile(s)
    code = pat.findall(html)
    return code
   
#########################开始干活############################
Url = 'http://quote.eastmoney.com/stocklist.html'#东方财富网股票数据连接地址
filepath = 'F:\\data\\'#定义数据文件保存路径
#实施抓取
code = getStackCode(getHtml(Url))
#获取所有股票代码(以6开头的,应该是沪市数据)集合
CodeList = []
for item in code:
    if item[0]=='6':
        CodeList.append(item)
#抓取数据并保存到本地csv文件
for code in CodeList:
    print('正在获取股票%s数据'%code)
    url = 'http://quotes.money.163.com/service/chddata.html?code=0'+code+\
        '&end=20171228&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP'
    urllib.request.urlretrieve(url, filepath+code+'.csv')


##########################将股票数据存入数据库###########################

#数据库名称和密码
name = 'xxxx'
password = 'xxxx'  #替换为自己的账户名和密码
#建立本地数据库连接(需要先开启数据库服务)
db = pymysql.connect('localhost', name, password, charset='utf8')
cursor = db.cursor()
#创建数据库stockDataBase
sqlSentence1 = "create database stockDataBase"
cursor.execute(sqlSentence1)#选择使用当前数据库
sqlSentence2 = "use stockDataBase;"
cursor.execute(sqlSentence2)

#获取本地文件列表
fileList = os.listdir(filepath)
#依次对每个数据文件进行存储
for fileName in fileList:
    data = pd.read_csv(filepath+fileName, encoding="gbk")
   #创建数据表,如果数据表已经存在,会跳过继续执行下面的步骤print('创建数据表stock_%s'% fileName[0:6])
    sqlSentence3 = "create table stock_%s" % fileName[0:6] + "(日期 date, 股票代码 VARCHAR(10),     名称 VARCHAR(10),\
                       收盘价 float,    最高价    float, 最低价 float, 开盘价 float, 前收盘 float, 涨跌额    float, \
                       涨跌幅 float, 换手率 float, 成交量 bigint, 成交金额 bigint, 总市值 bigint, 流通市值 bigint)"
    cursor.execute(sqlSentence3)
    except:
        print('数据表已存在!')

    #迭代读取表中每行数据,依次存储(整表存储还没尝试过)
    print('正在存储stock_%s'% fileName[0:6])
    length = len(data)
    for i in range(0, length):
        record = tuple(data.loc[i])
        #插入数据语句
        try:
            sqlSentence4 = "insert into stock_%s" % fileName[0:6] + "(日期, 股票代码, 名称, 收盘价, 最高价, 最低价, 开盘价, 前收盘, 涨跌额, 涨跌幅, 换手率, \
            成交量, 成交金额, 总市值, 流通市值) values ('%s',%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % record
            #获取的表中数据很乱,包含缺失值、Nnone、none等,插入数据库需要处理成空值
            sqlSentence4 = sqlSentence4.replace('nan','null').replace('None','null').replace('none','null')
            cursor.execute(sqlSentence4)
        except:
            #如果以上插入过程出错,跳过这条数据记录,继续往下进行
            break

#关闭游标,提交,关闭数据库连接
cursor.close()
db.commit()
db.close()


###########################查询刚才操作的成果##################################

#重新建立数据库连接
db = pymysql.connect('localhost', name, password, 'stockDataBase', charset='utf8)
cursor = db.cursor()
#查询数据库并打印内容
cursor.execute('select * from stock_600000')
results = cursor.fetchall()
for row in results:
    print(row)
#关闭
cursor.close()
db.commit()
db.close()
最佳答案
2022-7-20 22:12:22
qsyy216 发表于 2022-7-20 21:49
63行可以帮我改一下吗?
  1. #导入需要使用到的模块
  2. import urllib
  3. import re
  4. import pandas as pd
  5. import pymysql
  6. import os

  7. #爬虫抓取网页函数
  8. def getHtml(url):
  9.     html = urllib.request.urlopen(url).read()
  10.     html = html.decode('gbk')
  11.     return html

  12. #抓取网页股票代码函数
  13. def getStackCode(html):
  14.     s = r'<li><a target="_blank" href="http://quote.eastmoney.com/\S\S(.*?).html">'
  15.     pat = re.compile(s)
  16.     code = pat.findall(html)
  17.     return code
  18.    
  19. #########################开始干活############################
  20. Url = 'http://quote.eastmoney.com/stocklist.html'#东方财富网股票数据连接地址
  21. filepath = 'F:\\data\\'#定义数据文件保存路径
  22. #实施抓取
  23. code = getStackCode(getHtml(Url))
  24. #获取所有股票代码(以6开头的,应该是沪市数据)集合
  25. CodeList = []
  26. for item in code:
  27.     if item[0]=='6':
  28.         CodeList.append(item)
  29. #抓取数据并保存到本地csv文件
  30. for code in CodeList:
  31.     print('正在获取股票%s数据'%code)
  32.     url = 'http://quotes.money.163.com/service/chddata.html?code=0'+code+\
  33.         '&end=20171228&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP'
  34.     urllib.request.urlretrieve(url, filepath+code+'.csv')


  35. ##########################将股票数据存入数据库###########################

  36. #数据库名称和密码
  37. name = 'xxxx'
  38. password = 'xxxx'  #替换为自己的账户名和密码
  39. #建立本地数据库连接(需要先开启数据库服务)
  40. db = pymysql.connect('localhost', name, password, charset='utf8')
  41. cursor = db.cursor()
  42. #创建数据库stockDataBase
  43. sqlSentence1 = "create database stockDataBase"
  44. cursor.execute(sqlSentence1)#选择使用当前数据库
  45. sqlSentence2 = "use stockDataBase;"
  46. cursor.execute(sqlSentence2)

  47. #获取本地文件列表
  48. fileList = os.listdir(filepath)
  49. #依次对每个数据文件进行存储
  50. for fileName in fileList:
  51.     try:
  52.         data = pd.read_csv(filepath+fileName, encoding="gbk")
  53.        #创建数据表,如果数据表已经存在,会跳过继续执行下面的步骤print('创建数据表stock_%s'% fileName[0:6])
  54.         sqlSentence3 = "create table stock_%s" % fileName[0:6] + "(日期 date, 股票代码 VARCHAR(10),     名称 VARCHAR(10),\
  55.                            收盘价 float,    最高价    float, 最低价 float, 开盘价 float, 前收盘 float, 涨跌额    float, \
  56.                            涨跌幅 float, 换手率 float, 成交量 bigint, 成交金额 bigint, 总市值 bigint, 流通市值 bigint)"
  57.         cursor.execute(sqlSentence3)
  58.     except:
  59.         print('数据表已存在!')

  60.     #迭代读取表中每行数据,依次存储(整表存储还没尝试过)
  61.     print('正在存储stock_%s'% fileName[0:6])
  62.     length = len(data)
  63.     for i in range(0, length):
  64.         record = tuple(data.loc[i])
  65.         #插入数据语句
  66.         try:
  67.             sqlSentence4 = "insert into stock_%s" % fileName[0:6] + "(日期, 股票代码, 名称, 收盘价, 最高价, 最低价, 开盘价, 前收盘, 涨跌额, 涨跌幅, 换手率, \
  68.             成交量, 成交金额, 总市值, 流通市值) values ('%s',%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % record
  69.             #获取的表中数据很乱,包含缺失值、Nnone、none等,插入数据库需要处理成空值
  70.             sqlSentence4 = sqlSentence4.replace('nan','null').replace('None','null').replace('none','null')
  71.             cursor.execute(sqlSentence4)
  72.         except:
  73.             #如果以上插入过程出错,跳过这条数据记录,继续往下进行
  74.             break

  75. #关闭游标,提交,关闭数据库连接
  76. cursor.close()
  77. db.commit()
  78. db.close()


  79. ###########################查询刚才操作的成果##################################

  80. #重新建立数据库连接
  81. db = pymysql.connect('localhost', name, password, 'stockDataBase', charset='utf8')
  82. cursor = db.cursor()
  83. #查询数据库并打印内容
  84. cursor.execute('select * from stock_600000')
  85. results = cursor.fetchall()
  86. for row in results:
  87.     print(row)
  88. #关闭
  89. cursor.close()
  90. db.commit()
  91. db.close()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-7-20 21:45:17 | 显示全部楼层
本帖最后由 青出于蓝 于 2022-7-20 21:46 编辑
  1. #导入需要使用到的模块
  2. import urllib
  3. import re
  4. import pandas as pd
  5. import pymysql
  6. import os

  7. #爬虫抓取网页函数
  8. def getHtml(url):
  9.     html = urllib.request.urlopen(url).read()
  10.     html = html.decode('gbk')
  11.     return html

  12. #抓取网页股票代码函数
  13. def getStackCode(html):
  14.     s = r'<li><a target="_blank" href="http://quote.eastmoney.com/\S\S(.*?).html">'
  15.     pat = re.compile(s)
  16.     code = pat.findall(html)
  17.     return code
  18.    
  19. #########################开始干活############################
  20. Url = 'http://quote.eastmoney.com/stocklist.html'#东方财富网股票数据连接地址
  21. filepath = 'F:\\data\\'#定义数据文件保存路径
  22. #实施抓取
  23. code = getStackCode(getHtml(Url))
  24. #获取所有股票代码(以6开头的,应该是沪市数据)集合
  25. CodeList = []
  26. for item in code:
  27.     if item[0]=='6':
  28.         CodeList.append(item)
  29. #抓取数据并保存到本地csv文件
  30. for code in CodeList:
  31.     print('正在获取股票%s数据'%code)
  32.     url = 'http://quotes.money.163.com/service/chddata.html?code=0'+code+\
  33.         '&end=20171228&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP'
  34.     urllib.request.urlretrieve(url, filepath+code+'.csv')


  35. ##########################将股票数据存入数据库###########################

  36. #数据库名称和密码
  37. name = 'xxxx'
  38. password = 'xxxx'  #替换为自己的账户名和密码
  39. #建立本地数据库连接(需要先开启数据库服务)
  40. db = pymysql.connect('localhost', name, password, charset='utf8')
  41. cursor = db.cursor()
  42. #创建数据库stockDataBase
  43. sqlSentence1 = "create database stockDataBase"
  44. cursor.execute(sqlSentence1)#选择使用当前数据库
  45. sqlSentence2 = "use stockDataBase;"
  46. cursor.execute(sqlSentence2)

  47. #获取本地文件列表
  48. fileList = os.listdir(filepath)
  49. #依次对每个数据文件进行存储
  50. for fileName in fileList:
  51.     data = pd.read_csv(filepath+fileName, encoding="gbk")
  52.    #创建数据表,如果数据表已经存在,会跳过继续执行下面的步骤print('创建数据表stock_%s'% fileName[0:6])
  53.     sqlSentence3 = "create table stock_%s" % fileName[0:6] + "(日期 date, 股票代码 VARCHAR(10),     名称 VARCHAR(10),\
  54.                        收盘价 float,    最高价    float, 最低价 float, 开盘价 float, 前收盘 float, 涨跌额    float, \
  55.                        涨跌幅 float, 换手率 float, 成交量 bigint, 成交金额 bigint, 总市值 bigint, 流通市值 bigint)"
  56.     cursor.execute(sqlSentence3)
  57.     except:
  58.         print('数据表已存在!')

  59.     #迭代读取表中每行数据,依次存储(整表存储还没尝试过)
  60.     print('正在存储stock_%s'% fileName[0:6])
  61.     length = len(data)
  62.     for i in range(0, length):
  63.         record = tuple(data.loc[i])
  64.         #插入数据语句
  65.         try:
  66.             sqlSentence4 = "insert into stock_%s" % fileName[0:6] + "(日期, 股票代码, 名称, 收盘价, 最高价, 最低价, 开盘价, 前收盘, 涨跌额, 涨跌幅, 换手率, \
  67.             成交量, 成交金额, 总市值, 流通市值) values ('%s',%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % record
  68.             #获取的表中数据很乱,包含缺失值、Nnone、none等,插入数据库需要处理成空值
  69.             sqlSentence4 = sqlSentence4.replace('nan','null').replace('None','null').replace('none','null')
  70.             cursor.execute(sqlSentence4)
  71.         except:
  72.             #如果以上插入过程出错,跳过这条数据记录,继续往下进行
  73.             break

  74. #关闭游标,提交,关闭数据库连接
  75. cursor.close()
  76. db.commit()
  77. db.close()


  78. ###########################查询刚才操作的成果##################################

  79. #重新建立数据库连接
  80. db = pymysql.connect('localhost', name, password, 'stockDataBase', charset='utf8)
  81. cursor = db.cursor()
  82. #查询数据库并打印内容
  83. cursor.execute('select * from stock_600000')
  84. results = cursor.fetchall()
  85. for row in results:
  86.     print(row)
  87. #关闭
  88. cursor.close()
  89. db.commit()
  90. db.close()
复制代码


这是你的代码,63行,有except没有try?
91行少一个引号
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-7-20 21:49:38 | 显示全部楼层
青出于蓝 发表于 2022-7-20 21:45
这是你的代码,63行,有except没有try?
91行少一个引号

63行可以帮我改一下吗?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-7-20 22:12:22 | 显示全部楼层    本楼为最佳答案   
qsyy216 发表于 2022-7-20 21:49
63行可以帮我改一下吗?
  1. #导入需要使用到的模块
  2. import urllib
  3. import re
  4. import pandas as pd
  5. import pymysql
  6. import os

  7. #爬虫抓取网页函数
  8. def getHtml(url):
  9.     html = urllib.request.urlopen(url).read()
  10.     html = html.decode('gbk')
  11.     return html

  12. #抓取网页股票代码函数
  13. def getStackCode(html):
  14.     s = r'<li><a target="_blank" href="http://quote.eastmoney.com/\S\S(.*?).html">'
  15.     pat = re.compile(s)
  16.     code = pat.findall(html)
  17.     return code
  18.    
  19. #########################开始干活############################
  20. Url = 'http://quote.eastmoney.com/stocklist.html'#东方财富网股票数据连接地址
  21. filepath = 'F:\\data\\'#定义数据文件保存路径
  22. #实施抓取
  23. code = getStackCode(getHtml(Url))
  24. #获取所有股票代码(以6开头的,应该是沪市数据)集合
  25. CodeList = []
  26. for item in code:
  27.     if item[0]=='6':
  28.         CodeList.append(item)
  29. #抓取数据并保存到本地csv文件
  30. for code in CodeList:
  31.     print('正在获取股票%s数据'%code)
  32.     url = 'http://quotes.money.163.com/service/chddata.html?code=0'+code+\
  33.         '&end=20171228&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP'
  34.     urllib.request.urlretrieve(url, filepath+code+'.csv')


  35. ##########################将股票数据存入数据库###########################

  36. #数据库名称和密码
  37. name = 'xxxx'
  38. password = 'xxxx'  #替换为自己的账户名和密码
  39. #建立本地数据库连接(需要先开启数据库服务)
  40. db = pymysql.connect('localhost', name, password, charset='utf8')
  41. cursor = db.cursor()
  42. #创建数据库stockDataBase
  43. sqlSentence1 = "create database stockDataBase"
  44. cursor.execute(sqlSentence1)#选择使用当前数据库
  45. sqlSentence2 = "use stockDataBase;"
  46. cursor.execute(sqlSentence2)

  47. #获取本地文件列表
  48. fileList = os.listdir(filepath)
  49. #依次对每个数据文件进行存储
  50. for fileName in fileList:
  51.     try:
  52.         data = pd.read_csv(filepath+fileName, encoding="gbk")
  53.        #创建数据表,如果数据表已经存在,会跳过继续执行下面的步骤print('创建数据表stock_%s'% fileName[0:6])
  54.         sqlSentence3 = "create table stock_%s" % fileName[0:6] + "(日期 date, 股票代码 VARCHAR(10),     名称 VARCHAR(10),\
  55.                            收盘价 float,    最高价    float, 最低价 float, 开盘价 float, 前收盘 float, 涨跌额    float, \
  56.                            涨跌幅 float, 换手率 float, 成交量 bigint, 成交金额 bigint, 总市值 bigint, 流通市值 bigint)"
  57.         cursor.execute(sqlSentence3)
  58.     except:
  59.         print('数据表已存在!')

  60.     #迭代读取表中每行数据,依次存储(整表存储还没尝试过)
  61.     print('正在存储stock_%s'% fileName[0:6])
  62.     length = len(data)
  63.     for i in range(0, length):
  64.         record = tuple(data.loc[i])
  65.         #插入数据语句
  66.         try:
  67.             sqlSentence4 = "insert into stock_%s" % fileName[0:6] + "(日期, 股票代码, 名称, 收盘价, 最高价, 最低价, 开盘价, 前收盘, 涨跌额, 涨跌幅, 换手率, \
  68.             成交量, 成交金额, 总市值, 流通市值) values ('%s',%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % record
  69.             #获取的表中数据很乱,包含缺失值、Nnone、none等,插入数据库需要处理成空值
  70.             sqlSentence4 = sqlSentence4.replace('nan','null').replace('None','null').replace('none','null')
  71.             cursor.execute(sqlSentence4)
  72.         except:
  73.             #如果以上插入过程出错,跳过这条数据记录,继续往下进行
  74.             break

  75. #关闭游标,提交,关闭数据库连接
  76. cursor.close()
  77. db.commit()
  78. db.close()


  79. ###########################查询刚才操作的成果##################################

  80. #重新建立数据库连接
  81. db = pymysql.connect('localhost', name, password, 'stockDataBase', charset='utf8')
  82. cursor = db.cursor()
  83. #查询数据库并打印内容
  84. cursor.execute('select * from stock_600000')
  85. results = cursor.fetchall()
  86. for row in results:
  87.     print(row)
  88. #关闭
  89. cursor.close()
  90. db.commit()
  91. db.close()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-7-20 22:17:36 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-12 11:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表