前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >第六篇 爬虫技术之天天基金网(4) 基金档案信息获取篇

第六篇 爬虫技术之天天基金网(4) 基金档案信息获取篇

作者头像
python编程从入门到实践
发布2019-10-22 16:43:48
1.2K0
发布2019-10-22 16:43:48
举报

hello,大家好,上一次我们已经学会了如何抓取基金排名的数据。有人可能要问了,那我想了解一下每只基金的详细情况那该如何做呢,不急,今天我们就来给大家分析一下在获取到排名列表的情况下如何去获取每只基金的基本档案信息。

我们上次获取的信息如上图所示,如何才能在此基础上获取到每只基金的档案数据呢?

比如我们就想获取:鹏华美国房地产这只基金的详细档案数据呢?我们还是先F12一下看一下本页面展示出的一些数据。

不知道大家有没有发现,我们鼠标悬浮在这只基金的代码上或者名称上后我们看红框中的内容,是否可以通过这个a标签的点击来到我们想要的页面呢?我们尝试点击一下看看:

通过点击果然来到了这个页面,那我们分析一下我们刚才跳转过来的url有什么样的特征呢?http://fund.eastmoney.com/206011.html 我们看一下 在这个url中出现了一串数字206011,这个数字是怎么来的代表什么意思呢?我们回过头来看一下我们刚才选择的这只基金的代码是多少? 两者相等吗?好了通过分析我们就可以得出一个结论:想要获取指定基金的详细信息就要使用url='http://fund.eastmoney.com/xxx.html'来请求数据,有人或许会说你说这这些正确吗,我呢为了给大家讲解所以就只举出一个例子,那是不是每条基金的数据都是如此产生,这个就留给大家验证吧,我可以先给大家一个结论就是所有的都是按照我们上面分析的那样处理的。

好的,既然我们已经分析出是如何跳转的以及其请求资源的url是如何构成的,那我们就开始写代码来实现上述的功能。【我们解析一下详情页面中这个基金的规模字段】

代码语言:javascript
复制
# -*- encoding: utf-8 -*-
# !/usr/bin/python
"""
@File    : day_day_funding_detail_scrapy.py
@Time    : 2019/10/20 15:18
@Author  : haishiniu
@Software: PyCharm
"""
# -*- encoding: utf-8 -*-
# !/usr/bin/python
"""
@File    : day_day_funding_scrapy.py
@Time    : 2019/10/13 17:34
@Author  : haishiniu
@Software: PyCharm
"""

import json
import requests
import logging
import random
from pyquery import PyQuery as pq
import sys
reload(sys)
sys.setdefaultencoding('utf8')


class FundScrapy(object):
    """
    天天基金网
    """

    def __init__(self):
        """
        初始化信息
        """
        self.session = requests.session()
        self.timeout = 60

    def get_main_info(self):
        """
        获取首页的信息
        :return: 
        """
        try:
            main_url = 'http://fund.eastmoney.com/'
            self.session.headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
            self.session.headers["Accept-Encoding"] = "gzip, deflate, br"
            self.session.headers["Accept-Language"] = "zh-CN,zh;q=0.9"
            self.session.headers["Connection"] = "keep-alive"
            self.session.headers["Host"] = "fund.eastmoney.com"
            self.session.headers["Upgrade-Insecure-Requests"] = "1"
            self.session.headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"

            main_response = self.session.get(main_url, verify=False, timeout=self.timeout).content
            self.session.headers["Referer"] = 'http://fund.eastmoney.com/data/fundranking.html'
            # 获取前10% 倒数5% order数据 -->总样本量:750
            page_list = [1]
            order_list = []
            hander_list = ['fund_code', 'fund_name', 'date', 'asset_value', 'asset_value', 'day_rate', 'wek_rate', 'one_m_rate',
                           'three_m_rate', 'six_m_rate', 'one_y_rate', 'two_y_rate', 'three_y_rate', 'this_y_rate', 'complate_day_rate']
            for i in page_list:
                v_value = random.random()
                fund_ranking_url = "http://fund.eastmoney.com/data/rankhandler.aspx?op=ph&dt=kf&ft=all&rs=&gs=0&sc=zzf&st=desc&sd=2018-08-03&ed=2019-08-03&qdii=&tabSubtype=,,,,,&pi=%s&pn=50&dx=1&v=%s" %(i, v_value)
                # print fund_ranking_url
                fund_ranking_response = self.session.get(fund_ranking_url, verify=False, timeout=self.timeout)
                fund_ranking_response.encode = 'utf8'
                fund_ranking_response = fund_ranking_response.text

                response_list_json = fund_ranking_response[fund_ranking_response.find('var rankData = {datas:['):fund_ranking_response.find(']')].replace("var rankData = {datas:[", "")
                response_list_json = response_list_json
                for i in response_list_json.split('"'):
                    if len(i.split(',')) < 10:
                        continue
                    order = i.split(',')
                    order_list.append(order)

            for i in order_list:
                try:
                    order = i[:16]
                    order_detail_url = 'http://fund.eastmoney.com/%s.html' % str(order[0])
                    # print order_detail_url
                    order_detail_response = self.session.get(order_detail_url, verify=False, timeout=self.timeout)
                    html_pq = pq(order_detail_response.content)
                    scale_funds = html_pq('.infoOfFund table tr').eq(0)('td').eq(1).text()
                    print scale_funds
                    # print html_pq('.infoOfFund table tr').eq(0)('td').eq(1).text().find("基金规模:")
                    # print html_pq('.infoOfFund table tr').eq(0)('td').eq(1).text().find("亿元")
                    print scale_funds[scale_funds.find("基金规模:"):scale_funds.find("亿元")].replace('基金规模:', '')

                except Exception as ex:
                    logging.exception(str(ex))

        except Exception as ex:
            logging.exception(str(ex))


if __name__ == "__main__":
    CRZY_SCRAPY = FundScrapy().get_main_info()

最终输出结果为:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-10-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 python编程从入门到实践 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档