python网络爬虫:股票数据定向爬取

百度股票(https://gupiao.baidu.com/stock/)属于静态网页数据,适合定向数据爬取;新浪股票(http://finance.sina.com.cn/stock/)数据存取在js文件中,属于动态数据,不适合定向爬取,所以选择百度股票(https://gupiao.baidu.com/stock/)作为爬取对象。PS:Robots协议没有禁止网络爬虫

步骤说明

步骤1: 从东方财富网获取股票列表

步骤2: 逐一获取股票代码,并增加到百度股票的链接中,最后对这些链接进行逐个的访问获得股票的信息 

步骤3: 将结果存储到文件

代码实现

爬取当天一天的股票数据(上海,深圳交易所的)

import requests
from bs4 import BeautifulSoup
import re

def getHTMLText(url, code="utf-8"):
    try:
        r = requests.get(url)
        r.raise_for_status()#抛出异常
        r.encoding = code#设定编码格式
        return r.text
    except:
        return ""

def getStockList(lst, stockURL):
    html = getHTMLText(stockURL, "GB2312")  #只获取htlm文本
    soup = BeautifulSoup(html, 'html.parser') #html解析,到这里把整个网站源代码排版整理干净
    a = soup.find_all('a')     #解析页面,找到所有的a标签
    for i in a:
        #a[1] =要闻
        #type(a[1]) = bs4.element.Tag
        try:
            #找到a标签中的href属性,并且判断属性中间的链接,把链接后面的数字取出来
            href = i.attrs['href']
            #a[1].attrs['href'] = 'http://finance.eastmoney.com/yaowen.html'
            #深圳交易所的代码以sz开头,上海交易所的代码以sh开头,股票的数字有6位构成,所以正则表达式可以写为[s][hz]\d{6}
            lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
        except:
            #try...except来对程序进行异常处理
            continue

def getStockInfo(lst, stockURL, fpath):
    count = 0
    for stock in lst:
        url = stockURL + stock + ".html"
        html = getHTMLText(url)#对一只股票进行操作
        try:
            if html=="":
                continue
            infoDict = {}
            soup = BeautifulSoup(html, 'html.parser')
            stockInfo = soup.find('div',attrs={'class':'stock-bets'})#find整理成以
的整段代码 #
#

# # 基金通乾 (500038) # # 已休市 2018-07-20 15:01:32 # #

#
# 0.94 # -- # 0.00% #
#
#
#
最高
--
#
最低
--
#
今开
--
#
昨收
0.94
#
成交额
--
#
成交量
--
#
净值
0.9515
#
折价率
-1.42
#
#
#
#
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]#find_all从所有的stockInfo取出name # # 基金通乾 (500038) # infoDict.update({'股票名称': name.text.split()[0]}) # text取出 ( ) 标签代码以外文本 # # 股票的其他信息存放在dt和dd标签中,其中dt表示股票信息的键域,dd标签是值域。获取全部的键和值: keyList = stockInfo.find_all('dt') valueList = stockInfo.find_all('dd') for i in range(len(keyList)): key = keyList[i].text#text可直接在
最高
提取 val = valueList[i].text#text可直接在
0.94
提取 infoDict[key] = val#值赋到字典的键中 with open(fpath, 'a', encoding='utf-8') as f: f.write( str(infoDict) + '\n' ) count = count + 1 print("\r当前进度: {:.2f}%".format(count*100/len(lst)),end="") except: count = count + 1 print("\r当前进度: {:.2f}%".format(count*100/len(lst)),end="") continue def main(): stock_list_url = 'http://quote.eastmoney.com/stocklist.html' stock_info_url = 'https://gupiao.baidu.com/stock/' output_file = 'D:/BaiduStockInfo.txt' slist=[] getStockList(slist, stock_list_url) getStockInfo(slist, stock_info_url, output_file) main()

 

你可能感兴趣的:(学习,笔记,python,网络爬虫,python,网络爬虫)