股票数据定向爬虫

股票数据定向爬虫

目的:获取上交所和深交所所有股票的名称和交易信息
输出:保存到文件中
技术路线:requests-bs4-re

候选数据网站的选择

选取原则:股票信息静态存于HTML页面中,非js代码生成,没有Robots协议限制
选取方法:浏览器F12,源代码查看

数据网站的确定

获取股票列表
东方财富网:http://quote.eastmoney.com/stocklist.html
股票列表
获取个股信息
百度股票:http://gupiao.baidu.com/stock/
单个股票:http://gupiao.baidu.com/stock/sz002439.html
在这里插入图片描述

原理分析

查看百度股票每只股票的网址:
https://gupiao.baidu.com/stock/sz300023.html
可以发现网址中有一个编号300023正好是这只股票的编号,sz表示的深圳交易所。因此我们构造的程序结构如下:
步骤1: 从东方财富网获取股票列表;
步骤2: 逐一获取股票代码,并增加到百度股票的链接中,最后对这些链接进行逐个的访问获得股票的信息;
步骤3: 将结果存储到文件。

查看百度个股信息网页的源代码,每只股票的信息在html代码中的存储方式如下
在这里插入图片描述
每一个信息源对应一个信息值,即采用键值对的方式进行存储
在python中键值对的方式可以用字典类型
因此,在本项目中,使用字典来存储每只股票的信息,然后再用字典把所有股票的信息记录起来,最后将字典中的数据输出到文件中

代码编写
第一步:获得html网页数据
def getHTMLText(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""
第二步:html代码解析程序

在这里插入图片描述

a标签的href属性中的网址链接里面有每只股票的对应的号码,因此我们只要把网址里面对应股票的号码解析出来即可

html = getHTMLText(stockURL) #获得该页面信息

soup = BeautifulSoup(html,'html.parser')
    a = soup.find_all('a') #解析页面找到所有的a标签
对a标签中的每一个进行遍历来进行相关的处理 找到a标签中的href属性,并且判断属性中间的链接,把链接后面的数字取出来,在这里可以使用正则表达式来进行匹配。由于深圳交易所的代码以sz开头,上海交易所的代码以sh开头,股票的数字有6位构成,所以正则表达式可以写为[s][hz]\d{6};
由于在html中有很多的a标签,但是有些a标签中没有href属性,因此上述程序在运行的时候出现异常,所有对上述的程序还要进行try…except来对程序进行异常处理
for i in a :
        try:
            href = i.attrs['href']
            lst.append(re.findall(r'[s][hz]\d{6}',href)[0]
        except:
            continue

对东方财富网页面解析的完整代码如下

def getStockList(lst,stockURL):
    html = getHTMLText(stockURL,'GB2312')
    soup = BeautifulSoup(html,'html.parser')
    a = soup.find_all('a')
    for i in a :
        try:
            href = i.attrs['href']
            #以s开头,中间是h或z,后面再接六位数字
            lst.append(re.findall(r'[s][hz]\d{6}',href)[0])
        except:
            continue
第三步 获得百度股票网链接描述单只股票的信息

在这里插入图片描述
股票的信息就存在上图所示的html代码中,因此我们需要对这段html代码进行解析。过程如下:
1.百度股票网的网址为:
https://gupiao.baidu.com/stock/
一只股票信息的网址为:
https://gupiao.baidu.com/stock/sz300023.html
所以只要百度股票网的网址+每只股票的代码即可
因此对getStockList函数返回的列表进行遍历即可,代码如下:

for stock in lst:
        url = stockURL + stock +'.html'
        html = getHTMLText(url)

2.获得网页的html代码

html = getHTMLText(url)

3.对html代码进行解析

soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div',attrs={'class':'stock-bets'})

4.股票名称在bets-name标签内,继续解析

infoDict = {}
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称': name.text.split()[0]}) #split:股票名称空格后面的部分

5.观察到股票的其他信息存放在dt和dd标签中,其中dt表示股票信息的键域,dd标签是值域。获取全部的键和值:

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

6.把字典中的数据存入外部文件中

with open(fpath,'a',encoding='utf-8') as f:
                    f.write(str(infoDict) + '\n')

完整代码:

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'})
            
            if isinstance(stockInfo,bs4.element.Tag):
                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:
                    f.write(str(infoDict) + '\n')
                    count += 1
                    print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end='')                    
        except:
            print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end='')
            traceback.print_exc()
            continue
第四步:编写主函数,调用上述函数
def main():
    stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
    stock_info_url = 'http://gupiao.baidu.com/stock/' 
    output_file = 'C:/Users/Administrator/Desktop/Python网络爬虫与信息提取/BaiduStockInfo.txt'
    slist = []
    getStockList(slist,stock_list_url)
    getStockInfo(slist,stock_info_url,output_file)

项目完整程序

import requests
from bs4 import BeautifulSoup
import traceback
import re
import bs4

def getHTMLText(url,code='utf-8'): #使用code提高解析效率
    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')
    soup = BeautifulSoup(html,'html.parser')
    a = soup.find_all('a')
    for i in a :
        try:
            href = i.attrs['href']
            #以s开头,中间是h或z,后面再接六位数字
            lst.append(re.findall(r'[s][hz]\d{6}',href)[0])
        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'}            
            if isinstance(stockInfo,bs4.element.Tag):
                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:
                    f.write(str(infoDict) + '\n')
                    count += 1
                    print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end='')
                    #打印爬取进度
        except:
            print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end='')
            traceback.print_exc()
            continue
        
def main():
    stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
    stock_info_url = 'http://gupiao.baidu.com/stock/' 
    output_file = 'C:/Users/Administrator/Desktop/Python网络爬虫与信息提取/BaiduStockInfo.txt'
    slist = []
    getStockList(slist,stock_list_url)
    getStockInfo(slist,stock_info_url,output_file)

main()

结果预览图

在这里插入图片描述

### 使用 Node.js 和 Python 进行股票数据抓取 对于希望开发或获取用于抓取股票数据的爬虫软件或工具的需求,可以考虑两种主要技术栈:Node.js 和 Python。 #### 利用 Node.js 抓取股票数据 Node.js 提供了一个异步事件驱动环境,非常适合处理I/O密集型应用如Web爬虫。通过使用像 `axios` 或者 `node-fetch` 来发起HTTP请求,并结合 Cheerio 库解析HTML文档,能够轻松实现静态页面上的股票信息采集[^1]。 ```javascript const axios = require('axios'); const cheerio = require('cheerio'); async function fetchStockData(url) { try { const response = await axios.get(url); let $ = cheerio.load(response.data); // 假设我们要找的是某个特定表格中的股价 $('table tr').each((i, element) => { console.log($(element).text()); }); } catch (error) { console.error(`Error fetching data from ${url}:`, error.message); } } ``` #### 使用 Python 实现更复杂的功能 Python 是另一个广泛应用于网络爬虫的语言选项。它拥有丰富的第三方库支持,例如 Scrapy 框架可用于构建大型项目;而 BeautifulSoup 结合 requests 可快速搭建小型脚本完成简单任务。特别是当面对JavaScript渲染的内容时,Selenium WebDriver 成为了不可或缺的选择之一[^2]。 ```python import requests from bs4 import BeautifulSoup def get_stock_data(url): headers = {'User-Agent': 'Mozilla/5.0'} page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, "html.parser") # 查找并打印所有包含价格标签的div元素内的文本 prices = [item.text.strip() for item in soup.find_all("div", class_="price")] return prices ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值