股票数据定向爬虫

本文介绍了一个Python爬虫程序,该程序从东方财富网抓取股票URL,通过正则表达式提取上海和深圳股票代码,并结合百度股市通查询完整股票信息。程序利用requests、bs4和re库,将爬取的数据保存到本地TXT文件,同时展示了进度条提升用户体验。由于部分股票信息缺失,实际结果可能只包含股票名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本程序用两个主要url网址:东方财富网以及百度股市通。采用requests-bs4-re技术路线爬取了整个东方财富网的所有股票的信息并保存在本地D盘下的新建的TXT文本中。

1、爬取url网页获得html页面:
def getHTMLText(url, code="utf-8"):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = code
        return r.text
    except:
        return ""

网页默认编码为“utf-8”编码,比

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

这个方法可以爬取速度更加快速。

2、在东方财富网上截取股票信息上海股票和深圳股票的最后字符段,用来接到百度股票网页后来查询股票信息:

这里查看东方财富网网页的源代码,如下图为部分代码:


用以下代码中正则表达式匹配sh/z+6个数字到lst列表中:

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']
            lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
        except:
            continue
3、将截取到的字符串连接到百度股票后查询股票完整信息:

先在百度股票中查询一个股票并查看其源代码如下:


很明显可以看出股票的基本信息都在<dt>与<dd>标签中,将两个标签中的内容存于字典中并保存在本地。此代码还有个利用进度条读条的方法来增加用户体验(注意不要再idle中执行此程序,否则进度条不会自动在本行刷新,而是保存一个股票的信息后就跳转到下一行)

然后写出爬取股票信息的代码:

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'})
 
            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 = 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
4、最后,贴出本实验的完整代码:
import requests
from bs4 import BeautifulSoup
import traceback
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")
    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):
    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'})
 
            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 = 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()

以下是程序运行的截图:


因东方财富网上有些股票已经消失了,所以转到百度股票查看具体的信息时只会为空,爬取下来的信息中只有简单的股票名称而没有具体的信息。

### 使用 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 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值