搜索
您的当前位置:首页正文

股票数据定向爬虫

来源:二三娱乐

同济大学开源软件协会 Tommy

python运行界面 本地txt文件 代码开头需要赋值的空字符串s赋值之后的样子,后面还有很多html代码没有显示 html代码中含有股票代码的重点内容部分
import requests
from bs4 import BeautifulSoup
import traceback
import re

s = '''%%'''  
stock_info_url = 
output_file = 'D:/BaiduStockInfo4.txt'
slist=[]
slist = re.findall(r"[s][hz]\d{6}",s) #从字符串s中通过正则表达式提取出所有股票代码
def getHTMLText(url, code="utf-8"):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = code
        return r.text
    except:
        return ""
def getStockInfo(lst, stockURL, fpath):
    count = 0
    for stock in lst:
        url = stockURL + stock + ".html" # 构造每只股票访问百度股票的url
        html = getHTMLText(url)
        try:
            if html=="":
                continue
            infoDict = {}
            soup = BeautifulSoup(html, 'html.parser')
            stockInfo = soup.find('div',attrs={'class':'stock-bets'})
 
            name = stockInfo.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
                val = valueList[i].text
                infoDict[key] = val
             
            with open(fpath, 'a', encoding='utf-8') as f:
                print(str(infoDict) + '\n')
                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
getStockInfo(slist, stock_info_url, output_file)
Top