小白学爬虫笔记14---例 股票数据定向爬虫

例 股票数据定向爬虫

功能描述

  • 目标:获取上交所和深交所所有股票的名称和交易信息
    • 价格等
  • 输出:保存到文件中
  • 技术路线:requests-bs4-re
  • 候选网站
    • http://finance.sina.com.cn/stock/
    • https://gupiao.baidu.com/stock/
    • quote.eastmoney.com/stocklist.html/
  • 选取原则:股票信息静态存在于HTML页面中,非js代码生成,没有Robots协议限制
  • 浏览器F12,源代码查看
  • 选取心态:不要纠结于某个网站,多找信息源

 

import requests
from bs4 import BeautifulSoup
import traceback
import re

def getHTMLText(url):
    try:
        r = requests.get(url,timeout = 30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""   

def getStockList(lst,stockHTML)
    html = getHTMLText(stockURL)
    soup = BeautifulSoup(html, 'html.parser')
    a = soup.find_all('a')
    for i in a:
        try: # 筛选
            href = i.attrs['href']
            lst.append(re.findall(r"[s][hz]\d{6}",href)[0]
        except:
            continue

def getStockInfo(lst,stockURL, fpath):
    for stock in lst:
        url = stockURL + stock + ".html"
        html = getHTMLText(url)
        try:
            if html == "":
                continue
            infoDict = {}
            soupt = Beautifulsoup(html,'html.parser')
            stockInfo = soup.find('div', attrs={'class':'stock-bets'})

            name = stckInfo.find_all(attrs={'class':'bets-name'})[0]
            infoDict.update({'股票名称':name.text.split()[0]})

            keyList = stockInfo.find_all('dt')
            valueList = stockInfo.find_all('dd')
            for i in range(len(keyList)):
                key = keyList[i].text
                value = valueList[i].text
                infoDict[key] = value

            with open(fpath,'a',encoding='utf-8') as f:
                f.write(str(infoDict) + '\n')
        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://BaiduStockInfo.txt'
    slist = []
    getStockList(slist, stock_list_url)
    getStockInfo(slist, stock_info_url,output_file)     
main()

优化

速度提高:编码识别的优化

 

def getHTMLText(url,code='utf-8'):
    try:
        r.requests.get(url)
        r.raise_for_status
        r.encoding = code
        return r.text
    except:
        return ""

体验提高:增加动态进度显示

    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

你可能感兴趣的:(笔记,python)