爬取股票信息,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()

1个回答

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

lpshappy3
22Keep going3 我修改了一下,还是没办法爬到数据,新手不是很懂,不过还是十分感谢你!
9 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问