Python网络爬虫与信息提取

(五)"股票数据定向爬虫"(学习笔记)|Py

2018-01-19  本文已影响716人  努力奋斗的durian

1."股票数据定向爬虫"实例介绍
2."股票数据定向爬虫"代码及显示结果
3."股票数据定向爬虫"实例编写
4."股票数据定向爬虫"实例优化
5.单元小结

网页链接【Python网络爬虫与信息提取】.MOOC. 北京理工大学
https://www.bilibili.com/video/av9784617/index_37.html#page=46

最近更新:2018-01-19

1."股票数据定向爬虫"实例介绍

1.1功能描述

1.2候选数据网站的选择


1.3程序的结构设计

我们点击百度股票各股的信息.我看一下浏览器的显示.我们发现在百度股票中,每一个各股的网页都有一个各股的编号.作为网页地址的一部分.而这个编号恰巧是股票对应的深圳交易所或上海交易所的股票代码.由此我们构造一个程序结构.大概分为三个步骤:


2."股票数据定向爬虫"代码及显示结果

2.1代码显示结果

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 = 'http://gupiao.baidu.com/stock/'
    output_file = 'D:/BaiduStockInfo.txt'
    slist = []
    getStockList(slist, stock_list_url)
    getStockInfo(slist, stock_info_url, output_file)
main()

3."股票数据定向爬虫"实例编写

3.1流程框架设计

整个程序定义四个函数的设计,具体如下:

def getHTMLText(url):
    return ""
def getStockList(lst,stockURL):
    return ""
def getStockInfo(lst,stockURL,fpath):
    return ""
def main():
    stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
    stock_info_url = 'http://gupiao.baidu.com/stock/'
    output_file = 'D:/BaiduStockInfo.txt'
    slist = []
    getStockList(slist, stock_list_url)
    getStockInfo(slist, stock_info_url, output_file)
main()

整个程序的主体框架编写完成

3.2具体函数的介绍

3.1.1 getHTMLText()

这个函数运用过很多次,因此直接将以前的代码套用即可.

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

这个函数是从东方财富网获得股票列表.打开东方财富网http://quote.eastmoney.com/stocklist.html对应的股票列表页面的源代码.点击右键,查看源代码,找一下股票其中所在的位置.发现所有的股票信息保持在a标签的信息内,a标签中href也就是链接属性中间的.html前面部分,这是每只股票的代码,我们需要把股票代码提取出来,就能获得所有的股票信息,的文件具体如下:

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.1.3 getStockList()

需要知道股票个股信息在百度股票网站上显示的源代码.随便找了一只个股易联众,在页面源代码中查找确定当天价格12.07作为搜索,如下:


在搜索结果的区域有很多与个股相关的信息,这些信息就是我们要获得的信息,这些信息封装在一个html的格式中如下:
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"股票数据定向爬虫"实例优化

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

对"股票数据定向爬虫"进行小优化,优化的目的是提高用户体验,即提高速度.只要采用requests以及BeautifulSoup都不会提高速度.大家对爬虫速度有很高的要求,用scrapy库.只提一个小区域代码的地方,提高速度,这个代码位置就是encoding.


修改前


修改后


修改前


修改后


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

在爬取的过程中,增加动态的显示,也就是代码在爬取页面的过程中,可能要爬取很多的页面,股票数据而言,有4000多个页面,需要一种动态的方法来显示进度.修改代码,增加一种不换行就可以显示的进度条.增加一个计数变量count,把初值赋为0,增加一个进度条,这个进度条打印当前爬取进度的百分比.



修改前


修改后

5.单元小结

上一篇 下一篇

猜你喜欢

热点阅读