22Keep going3 2019-05-03 17:36 采纳率: 0%
浏览 887

爬取股票信息,python没报错但不能爬取出结果!急求大神啊!!???

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import traceback
import re
import time
import requests

def GetHTMLSource(url):
 try:
  r=requests.get(url)
  r.raise_for_status ()
  r.encoding = r.apparent_encoding
  return r.text
 except:
  print ( "异常" )
  return ""


def SetFileName():
 dirname = time.strftime ( '%Y%m%d' , time.localtime ( time.time () ) ) #获取当前日期
 dirname += 'sh'
 return dirname

def getStockList(lst , stock_list_url): # 获得东方财富网上以sh6开头的股票代码
 html = GetHTMLSource ( stock_list_url )
 soupdata = BeautifulSoup ( html , 'html.parser' )
 a = soupdata.find_all ( 'a' ) # 用find_all方法遍历所有'a'标签,并取出在'a'标签里面的’href’数据
 for i in a:
  try:
   href = i.attrs[ 'href' ]
   lst.append ( re.findall ( r"sh6d{5}" , href )[ 0 ] )
  except:
   continue

def getStockInfo(lst , stock_info_url , fpath):
 ndate = time.strftime ( '%Y%m%d' , time.localtime ( time.time () ) )
 for stock in lst:
  url = stock_info_url + stock + '.html'
  html = GetHTMLSource ( url )
  try:
   if html == "":
    continue
    infoDict = {}
    soup = BeautifulSoup ( html, 'html.parser' )
    stockInfo = soup.find ( 'div' , attrs={'class': 'stock-bets'} )
    if stockInfo == None:
     continue
     keyData = stockInfo.find_all ( 'dt' )
     valueData = stockInfo.find_all ( 'dd' )
     inp = stock + "," + ndate + ","
     for i in range ( len ( keyData ) ):
      key = keyData[ i ].text
      val = valueData[ i ].text
      infoDict[ key ] = val
      inp += infoDict[ '最高' ] + "," + infoDict[ '换手率' ] + "," + infoDict[ '成交量' ] + "," + infoDict[ '成交额' ] + ""
      with open ( fpath , 'a' , encoding='utf-8' ) as f:
       f.write ( inp )
  except:
       traceback.print_exc ()
       continue



def main():
    stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
    stock_info_url = 'https://gupiao.baidu.com/stock/'
    output_file = 'D://a.txt'
    slist = []
    getStockList(slist,stock_list_url)
    getStockInfo(slist,stock_info_url,output_file)
main()

  • 写回答

2条回答 默认 最新

  • BuXianShan 2019-05-03 22:51
    关注

    你好,我调试了你的代码,发现 getStockList 函数的这一行出错了:
    lst.append ( re.findall ( r"sh6d{5}" , href )[ 0 ] )
    这里一直没有匹配到。所以lst列表一直为空,导致后面没有结果。
    希望可以帮到你。

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器