Python爬虫小实例:爬股票数据(作业3)

  1. 程序来源:中国大学MOOC网《网络爬虫与信息提取课程》
  2. 程序目的:获取上交所和深交所的部分股票信息,输出到文件。
  3. 涉及知识;requests库、BeautifulSoup库和re库
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  # 直接指定用utf-8解码
        return r.text
    except:
        return ""


def getStockList(lst, stockURL):
    html = getHTMLText(stockURL, "GB2312")  # 东方财富网用的是GB2312编码
    soup = BeautifulSoup(html, 'html.parser')
    a = soup.find_all('a')[:200]  # 股票代码在a标签中的href属性中。我们只取前100个a标签
    for i in a:
        try:
            href = i.attrs['href']
            lst.append(re.findall(r"\d{6}", href)[0])
        except:
            continue


def getStockInfo(lst, stockURL, fpath):
    count = 0
    for stock in lst:
        url = stockURL + stock  # 每只股票的信息的链接
        html = getHTMLText(url)
        try:
            if html == "":
                continue
            infoDict = {}  # 每只股票的信息都存在字典中
            soup = BeautifulSoup(html, 'html.parser')
            stockInfo = soup.find('div', attrs={'class': 'stock-info'})
            name = stockInfo.find_all(attrs={'class': 'stock-name'})[0]
            infoDict.update({'股票名称': name.text.split()[0]})  # .text可以取出标签中的字符串
            keyList = stockInfo.find_all('dt')[:4]  # 只取股票的前4个信息
            valueList = stockInfo.find_all('dd')[:4]
            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="")  # \r表示返回到当前行的起始位置,打印的内容会覆盖之前打印的内容
                # 每次print之后,会自动换行。end用来取消自动换行。
        except:
            count = count + 1
            print("\r当前进度: {:.2f}%".format(count * 100 / len(lst)), end="")
            continue


def main():
    stock_list_url = 'https://quote.eastmoney.com/stock_list.html'  # 从东方财富网获取每只股票的代码
    stock_info_url = 'https://www.laohu8.com/stock/'  # 从老虎社区网站获取每只股票的信息
    output_file = 'BaiduStockInfo.txt'
    slist = []
    getStockList(slist, stock_list_url)
    getStockInfo(slist, stock_info_url, output_file)


main()

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值