爬取股票信息,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()
22Keep going3
2019/05/03 17:36- python
- 点赞
- 收藏
- 回答
2个回复
