【实例】--股票数据定向爬取

从股票列表网页获取股票代码

根据股票代码去股票详情页面获取股票详细信息

1、 股票列表页面

  凤凰网财经—股票信息

  http://app.finance.ifeng.com/list/stock.php?t=ha&f=chg_pct&o=desc&p=1

2、 股票详细信息

  老虎社区—股票详情

  https://www.laohu8.com/stock/600210

股票数据定向爬取思路

扫描二维码关注公众号,回复: 9335897 查看本文章

1、 查看网站robots协议,查看网站是否可以爬取

2、 查看网页源代码,查看网页信息是否可以直接爬取

3、 爬取网页信息

4、 解析网页,获取页面信息

在HTML页面中

1)      对于非常有特征的数据,可以直接用正则表达式搜索到

2)      信息存在的区域相对固定,则用BeautifulSoup定位标签位置,再用正则表达式获取

5、 将获取的信息储存到文件中

优化代码

1、提高爬虫速度

     直接赋值编码

2、提高程序运行体验(运行时间较长的程序)

  增加动态精度显示

import requests
from bs4 import BeautifulSoup
import re
import traceback

def getHTMLText(url, code='utf-8'):
   try:
       r = requests.get(url)
       r.raise_for_status()
       r.encoding = code
       return r.text
   except:
       print('爬取失败')

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]) ## 匹配 a 标签中 href 属性以 s 开头,中间是 h 或 z ,最后是6位数字
        except:
            continue

def getStockInfo(lst, stockURL, fpath):
    ## 去掉列表里的重复选项--将列表转换为集合再转换为列表
    lst = list(set(lst))
    count = 0
    for stock in lst:
        url = stockURL + stock[-6:]
        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':'name'})[0]
            price = stockInfo.find_all(attrs={'class': 'latest'})[0]
            infoDict.update({'股票名称':name.text.split()[0], '最新行情':price.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:
            traceback.print_exc()  ## 获得发生异常的错误信息
            continue

def main():
    stock_list_url = 'http://app.finance.ifeng.com/list/stock.php?t=ha'
    stock_info_url = 'https://www.laohu8.com/stock/'
    output_file = 'C:\\try\\StockInfo.txt'
    slist = []
    getStockList(slist, stock_list_url)
    getStockInfo(slist, stock_info_url, output_file)

main()

  

猜你喜欢

转载自www.cnblogs.com/motoharu/p/12346705.html