1+1网页数据爬虫+数据可视化

1+1网页数据爬虫+数据可视化

##很长时间没有更新,甚至在写代码时手都有点陌生,所以说代🐎这东西还是得经常操练,很多东西都是不用隔一段时间就忘了,当然保持良好得习惯和风格还是很重要滴###
#######话不多说开始操练(ps:本人使用得标编辑器是pycharm2018)###############
##本次所编写的事例:亚洲国家2019-1954年GDP数据排行
程序主要流程:

  1. 获取一层网页中对应国家以及其GDP数据的网页网址
  2. 获取二层网页中对应国家得GDP数据并保存在列表中
  3. 处理GDP数据适合pyecharts绘制数据图像
  4. 绘制各个国家2019-1954年GDP数据排行图

主要

##导入所需要得python第三方库

#亚洲国家GDP年度数据

import requests
from requests.exceptions import RequestException
from fake_useragent import UserAgent   #生成随机请求头
from lxml import etree
import re
from pyecharts.charts import Line    #折线图
from pyecharts import options    #设置标题

##设置目标一层网页地址,定义全局变量(ps:有时候全局变量非常好用)

#获取随机请求头
HEADERS = {
    "User-Agent":str(UserAgent().random)
}

############GDP数据首页##########################
BASE_DOMAIN = 'https://www.kylc.com/stats/global/yearly_overview/g_gdp_per_capita.html'

##############存放各个国家名称+年度GDP数据#########################################
data_country = []   #亚洲各个国家名称
data_GDP = []   #各个国家对应的GDP数据

#获取各个国家GDP数据网址连接

###############获取各个国家GDP数据网址连接############################################
def Country_link():
    country_urls = []
    i = 0
    try:
        res = requests.get(BASE_DOMAIN,headers=HEADERS,timeout=30)
        if  res.status_code == 200:
            res.encoding = res.apparent_encoding
            html = etree.HTML(res.text)  # 创建一个html对象
            countrys = html.xpath("/html/body/div[2]/div[1]/div[5]/div[2]/div[3]/div[2]/ul[1]/li/a/text()")  #国家名称
            links = html.xpath("/html/body/div[2]/div[1]/div[5]/div[2]/div[3]/div[2]/ul[1]/li/a/@href")  # xpath返回的是一个列表
            for country in countrys:
                country_url = {
                    country:links[i]
                }
                i = i + 1
                country_urls.append(country_url)
            return country_urls

        return None
    except  RequestException:    #捕获异常
        return  None

#解析各个国家年度GDP数据

############解析各个国家年度GDP数据######################################
def Country_datas(country,link):
    base_url = 'https://www.kylc.com'

    country_url = base_url + link
    res = requests.get(country_url, headers=HEADERS, timeout=30)
    html = etree.HTML(res.text)  # 创建一个html对象
    data = html.xpath('//table[@class="table"]/tbody/tr/td[2]/text()')  #返回一个列表对象,年度GDP数据
    data_country.append(country)
    data_GDP.append(data)
    print("解析成功{}次".format(data_country.index(country)+1))

#绘制各个国家GDP年度变化折线图

#############绘制各个国家GDP年度变化折线图#####################################
def GDP_line(data_country,data_GDP,years):
    bar = Line(init_opts=options.InitOpts(width="2000px"))  # 创建一个对象,初始化图标宽度和高度
    bar.add_xaxis(years[::-1])  # 添加横坐标数据
    for i in range(46):
        data_tem = data_process(data_GDP[i])
        bar.add_yaxis(data_country[i], data_tem[::-1], label_opts=options.LabelOpts(is_show=False))  # 添加纵坐标数据和坐标标识

    bar.set_global_opts(title_opts=options.TitleOpts(title="Asia_CountryGDP", subtitle="-数据截至2019年-"))  # 标题作为可选参数
    bar.render('Asia_CountryGDP.html')

#处理GDP数据格式 4.02万 (40,246) 3997

#########################处理GDP数据格式     4.02万 (40,246)    3997  #########
def data_process(data):
    data_tem = []
    for i in data:
        ret = re.search(r'\(.*?\)', i)
        if ret:
            data_new = ret.group().strip('()').replace(',','')
        else:
            data_new = i
        data_tem.append(int(data_new))

    for i in range(66-len(data)):    #补齐2019-1954数据
        data_tem.append(0)

    return data_tem

#生成年份数据2019-1954

##################生成数据年份######################
def years():
    year = 2019
    years = []  # 2019-1954年
    for i in range(66):
        years.append(str(year))
        year -= 1
    return years

#顶层函数

#顶层函数
def main():
    print("---开始获取亚洲国家GDP相关数据---")
    # 获取国家和对应GDP连接
    country_urls = Country_link()
    print("---获取各个亚洲国家和对应GDP连接成功---")

    #获取国家年度GDP数据
    for country_url in country_urls:
        for country,link in country_url.items():
            Country_datas(country,link)
    print("---解析各个亚洲国家GDP数据成功---")

    #绘制各个国家GDP年度变化折线图
    GDP_line(data_country, data_GDP,years())
    print("---亚洲各国GDP数据图绘制完成---")
    

#整体程序入口

if __name__ == '__main__':
    main()

#效果网页图片展示
在这里插入图片描述

本次亚洲国家GDP数据排行爬取以及可视化绘图代码完全按照最能直观理解方式编写,可能有些地方违反了python极致简洁得原则,希望大家相互交流学习!!!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值