当前位置:网站首页>Automatically update site statistics with actions

Automatically update site statistics with actions

2022-06-23 02:15:00 Qwe7

Get Baidu statistics open api Of token, utilize python Count Baidu api The returned statistics are downloaded and saved as json file , recycling JavaScript Read and process json data , Pass the processed data through echarts.js Draw as chart .

obtain token And site_id

Before that, I believe you have completed the registration of Baidu statistics and will be able to use Baidu statistics normally . About getting token and site_id. It is worth noting that the token It is valid for one month and needs to be reused every other month refresh_token Renew token So you can update token Save the link for token After the failure, you can directly use the link to update .

Use python Download the file

adopt 6 A link , We can get : Daily visit statistics within a year 、 Access map data 、 Monthly visit statistics 、 Source classification statistics 、 Search engine access statistics and external link access statistics ; adopt python Download and save . In order to avoid cross domain problems, the json Documentation needs and census.js In the same directory , Cross domain issues can be solved by This post Get to know . I'll show you the complete structure catalog first , You can create it in the same way .

javascript

source 
└── census
    └── index.md // Auxiliary statistics page rendering 
    └── census.js // Processing data 
    └──data
        └──get.py // Get saved data 
theme
└──matery
    └──layout
        └──census.ejs// Render as statistics page 

Create a new one according to the above directory get.py Write the following contents in the file :

python

import requests
import time, datetime

#  Start date of statistics 
start_date   = '20201101'
date         = datetime.datetime.now()
#  End date of Statistics 
end_date     = str(date.year) + (str(date.month) if date.month > 9 else ('0' + str(date.month))) + (str(date.day) if date.day > 9 else ('0' + str(date.day)))
# token and siteid
# It needs to be modified to your token and siteid
access_token = '121.*******'
site_id      = '16*******'
#  Baidu statistics API
dataUrl      = 'https://openapi.baidu.com/rest/2.0/tongji/report/getData?access_token=' + access_token + '&site_id=' + site_id
#  Count the number of visits  PV  Fill in  'pv_count', Count the number of visitors  UV  Fill in  'visitor_count', A choice 
metrics      = 'pv_count'
ips      = 'visitor_count'

def downFile(url, fileName, prefix=''):
    print('downloading :', url)
    down_res = requests.get(url)
    with open(prefix+fileName, 'wb') as f:
        f.write(down_res.content)
    print('writing :', prefix+fileName)

#  Visitor Map 
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=visit/district/a', 
    'map.json')

#  Access trends 
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=trend/time/a&gran=month', 
    'pv.json')
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + ips + '&method=trend/time/a&gran=month', 
    'uv.json')
#  Source of visit 
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=source/all/a', 
    'sources.json')

##  Search engine 
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=source/engine/a', 
    'engine.json')

##  External links 
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=source/link/a', 
    'link.json')

#  Visit the calendar 
'''
 To access the calendar, you need to get the data within one year , According to one year 365 Day count , It's about 52 A little more than a week , So there is a complete 52 row , The access method is only through the start date and year -1 that will do 
 And then the first 53 Disposal of rows ,python Medium date.weekday() The day of the week obtained is 0 On Monday , So pass (date.weekday()+1)%7 You can switch to 0 Corresponding to Sunday 
 So in 52 On a weekly basis , Minus weeks , You can get new start_date
'''
date       = datetime.datetime(date.year-1, date.month, date.day)
date       = datetime.datetime.fromtimestamp(date.timestamp()-3600*24*((date.weekday()+1)%7))
start_date = str(date.year) + (str(date.month) if date.month > 9 else ('0' + str(date.month))) + (str(date.day) if date.day > 9 else ('0' + str(date.day)))
downFile(dataUrl + '&method=overview/getTimeTrendRpt' + '&metrics=' + metrics + '&start_date=' + start_date + '&end_date=' + end_date,
    'calendar.json')
downFile(dataUrl + '&method=overview/getTimeTrendRpt' + '&metrics=' + ips + '&start_date=' + start_date + '&end_date=' + end_date,
    'ipcalendar.json')

Local testing : If you have python The environment can be direct cd Store in get.py The catalog of python get.py, Prompt that the library installation is missing . If you don't finish GitHubactions Integrated deployment can also be semi automatically updated periodically through this method , However, it is still recommended to make integrated deployment. It really smells good .

newly build md and ejs file

Create a new one as shown in the previous structure diagram index.md and census.ejs file .

stay index.md Write the following in :

---
title: census
date: 2020-10-31 10:11:28
type: "census"
layout: "census"
---

stay census.ejs Write the following in :

<%- partial('_partial/bg-cover') %>
<style>
  .journal {
    padding: 12px;
    border: 1px dashed #e6e6e6;
    color: #969696;
    position: relative;
    display: inline-block;
    width: 95%;
    background: #fbfbfb50;
    border-radius: 10px;
    font-size: 16px;
    margin: 12px auto;
  }
</style>
<script type="text/javascript" src="https://npm.elemecdn.com/[email protected]/dist/echarts.min.js"></script>
<script src="https://npm.elemecdn.com/[email protected]/map/js/china.js"></script>
<main class="content">
  <div class="container chip-container">
    <div class="card">
      <div class="card-content">
        <div class="tag-title center-align">
          <div class="journal">
            <div class="title center-align">“  Site statistics ”</div>
            “  since  2020-11-14  rise , Every time 12 Automatically update every hour  ”
          </div>
        </div>
        <div id="calendar_container" style="min-height: 200px; -webkit-tap-highlight-color: transparent; user-select: none; position: relative"></div>
        <div id="uv_container" style="min-width: 250px; height: 400px; margin-top: 50px; -webkit-tap-highlight-color: transparent; user-select: none; position: relative" ></div>
        <div id="pv_container" style="min-width: 250px; height: 400px; margin-top: 50px; -webkit-tap-highlight-color: transparent; user-select: none; position: relative" ></div>
        <div id="map_container" style="min-width: 250px; height: 400px; margin-top: 50px; -webkit-tap-highlight-color: transparent; user-select: none; position: relative" ></div>
        <div id="sources_container" style="min-width: 250px; height: 400px; margin-top: 50px; -webkit-tap-highlight-color: transparent; user-select: none; position: relative" ></div>
        <script src="/census/census.js"></script>
      </div>
    </div>
  </div>
</main>

calendar_container Container for visitor calendar graph ,uv_container Container for site visitor statistics ,pv_container Container for site traffic statistics ,map_container Container for accessing location maps for sites ,sources_container Container for analyzing pie charts for site visitor sources .

newly build census.js file

Create a new one as shown in the previous structure diagram census.js The file is written as follows :

javascript

var metrics     = 'pv_count' //  Count the number of visits  PV  Fill in  'pv_count', Count the number of visitors  UV  Fill in  'visitor_count', A choice 
var metricsName = (metrics === 'pv_count' ? ' Number of visits ' : (metrics === 'visitor_count' ? ' Number of visitors ' : ''))
function generatePieces(maxValue, colorBox) &#123;
    var pieces = [];
    var quotient = 1;
    var temp = &#123;'lt': 1, 'label': '0', 'color': colorBox[0]&#125;;
    pieces.push(temp);

    if (maxValue && maxValue >= 10) &#123;
        quotient = Math.floor(maxValue / 10)+1;
        for (var i = 1; i <= 10; i++) &#123;
            var temp = &#123;&#125;;
            if (i == 1)   temp.gte = 1;
            else   temp.gte = quotient * (i - 1);
            temp.lte = quotient * i;
            temp.color = colorBox[i];
            pieces.push(temp);
        &#125;
    &#125;
    return JSON.stringify(pieces);
&#125;

var append_div_visitcalendar = (parent, text) => &#123;
    if (parent !== null) &#123;
        if (typeof text === 'string') &#123;
            var temp = document.createElement('div');
            temp.innerHTML = text;
            var frag = document.createDocumentFragment();
            while (temp.firstChild) &#123;
                frag.appendChild(temp.firstChild)
            &#125;
            parent.appendChild(frag)
        &#125; else &#123;
            parent.appendChild(text)
        &#125;
    &#125;
&#125;;

function calChart () &#123;
    let script = document.createElement("script")
    fetch('/census/data/ipcalendar.json?date'+new Date()).then(data => data.json()).then(data => &#123;
        let date_arr = data.result.items[0];
        let value_arr = data.result.items[1];
        let calArr = [];
        let maxValue = 0, total = 0, weekdatacore = 0, thisweekdatacore = 0;
        let colorBox = ['#EBEDF0', '#90EE90', '#98FB98', '#32CD32', '#00FF00', '#7FFF00', '#3CB371', '#2E8B57', '#228B22', '#008000', '    #006400'];
        for (let i = 0; i < date_arr.length; i++) &#123;
            calArr.push([date_arr[i][0], value_arr[i][0] === '--' ? 0 : value_arr[i][0]] );
            maxValue = value_arr[i][0] > maxValue ? value_arr[i][0] : maxValue ;
            total += value_arr[i][0] === '--' ? 0 : value_arr[i][0];
        &#125;
        for (let i = date_arr.length-1; i >= date_arr.length-7; i--)   weekdatacore += value_arr[i][0] === '--' ? 0 : value_arr[i][0];
        for (let i = date_arr.length-1; i >= date_arr.length-30; i--)   thisweekdatacore += value_arr[i][0] === '--' ? 0 : value_arr[i][0];
        let calArrJson = JSON.stringify(calArr);
        script.innerHTML = `
        var calChart = echarts.init(document.getElementById("calendar_container"));
        var option = &#123;
            title: &#123; text: ' Visit the calendar ' &#125;,
            tooltip: &#123;
                padding: 10,
                backgroundColor: '#555',
                borderColor: '#777',
                borderWidth: 1,
                textStyle: &#123; color: '#fff' &#125;,
                formatter: function (obj) &#123;
                    var value = obj.value;
                    return '<div style="font-size: 14px;">' + value[0] + ':' + value[1] + '</div>';
                &#125;
            &#125;,
            visualMap: &#123;
                show: false,
                showLabel: true,
                min: 0,
                max: $&#123;maxValue&#125;,
                type: 'piecewise',
                orient: 'horizontal',
                left: 'center',
                bottom: 0,
                pieces: $&#123;generatePieces(maxValue, colorBox)&#125;
            &#125;,
            calendar: [&#123;
                left: 'center',
                range: ['$&#123;date_arr[0]&#125;', '$&#123;date_arr[date_arr.length-1]&#125;'],
                cellSize: [14, 14],
                splitLine: &#123;
                    show: false
                &#125;,
                itemStyle: &#123;
                    color: '#ebedf0',
                    borderColor: '#fff',
                    borderWidth: 2
                &#125;,
                yearLabel: &#123;
                    show: false
                &#125;,
                monthLabel: &#123;
                    nameMap: 'cn',
                    fontSize: 11
                &#125;,
                dayLabel: &#123;
                    formatter: '&#123;start&#125;  1st',
                    nameMap: 'cn',
                    fontSize: 11
                &#125;
            &#125;],
            series: [&#123;
                type: 'heatmap',
                coordinateSystem: 'calendar',
                calendarIndex: 0,
                data: $&#123;calArrJson&#125;,
            &#125;]    
        &#125;;
        calChart.setOption(option);`;
        let style = '<style>.number&#123;font-family: sans-serif, Arial;margin-top: 10px;text-align:center;width:100%;padding:10px;margin:0 auto;&#125;.contrib-column&#123;text-align:center;border-left:1px solid #ddd;border-top:1px solid #ddd;&#125;.contrib-column-first&#123;border-left:0;&#125;.table-column&#123;padding:10px;display:table-cell;flex:1;vertical-align:top;&#125;.contrib-number&#123;font-weight:400;line-height:1.3em;font-size:24px;display:block;&#125;.left.text-muted&#123;float:left;margin-left:9px;color:#767676;&#125;.left.text-muted a&#123;color:#4078c0;text-decoration:none;&#125;.left.text-muted a:hover&#123;text-decoration:underline;&#125;h2.f4.text-normal.mb-3&#123;display:none;&#125;.float-left.text-gray&#123;float:left;&#125;.position-relative&#123;width:100%;&#125;@media screen and (max-width:650px)&#123;.contrib-column&#123;display:none&#125;&#125;</style>';
        style = '<div style="display:flex;width:100%" class="number"><div class="contrib-column contrib-column-first table-column"><span class="text-muted"> Visited in the past year </span><span class="contrib-number">' + total + '</span><span class="text-muted">' + date_arr[0][0] + '&nbsp;-&nbsp;' + date_arr[date_arr.length-1][0] + '</span></div><div class="contrib-column table-column"><span class="text-muted"> lately 30 Day visit </span><span class="contrib-number">' + thisweekdatacore + '</span><span class="text-muted">' + date_arr[date_arr.length-30][0] + '&nbsp;-&nbsp;' + date_arr[date_arr.length-1][0] + '</span></div><div class="contrib-column table-column"><span class="text-muted"> lately 7 Day visit </span><span class="contrib-number">' + weekdatacore + '</span><span class="text-muted">' + date_arr[date_arr.length-7][0] + '&nbsp;-&nbsp;' + date_arr[date_arr.length-1][0] + '</span></div></div>' + style;

        document.getElementById("calendar_container").after(script);
        append_div_visitcalendar(calendar_container, style);
    &#125;).catch(function (error) &#123;
        console.log(error);
    &#125;);
&#125;
function get_year(s) &#123;
    return parseInt(s.substr(0, 4))
&#125;
function get_month(s) &#123;
    return parseInt(s.substr(5, 2))
&#125;
//  Browse volume 
function pvChart () &#123; 
    let script = document.createElement("script")
    fetch('/census/data/pv.json?date'+new Date()).then(data => data.json()).then(data => &#123;
        let date = new Date();
        let monthValueArr = &#123;&#125;;
        let monthName = data.result.items[0];
        let monthValue = data.result.items[1];
        for (let i =2020; i <= date.getFullYear(); i++)   monthValueArr[String(i)] = [ ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ];
        monthValueArr
        for (let i = 0; i < monthName.length; i++) &#123;
            let year = get_year(monthName[i][0]);
            let month = get_month(monthName[i][0]);
            monthValueArr[String(year)][String(month-1)] = monthValue[i][0];
        &#125; 
        script.innerHTML = `
        var pvChart = echarts.init(document.getElementById('pv_container'), 'light');
        var pvOption = &#123;
    color: ['#01C2F9', '#18D070', '#d223e7', '#3F77FE'],
    title: &#123;
        text: ' Site traffic statistics ',
        subtext: ' Data sources :  Baidu statistics ( since  2020/11/14  Start Statistics )',
        textStyle: &#123;
            color: '#504b4d',
        &#125;
    &#125;,
    legend: &#123;
        data: ['2020 Annual visits ', '2021 Annual visits '],
        // Revision year 
        bottom: 0,
        left: 'center',
        textStyle: &#123;
            color: '#504b4d',
        &#125;
    &#125;,
    tooltip: &#123;
        trigger: 'axis'
    &#125;,
    toolbox: &#123;
        show: true,
        feature: &#123;
            mark: &#123;
                show: true
            &#125;,
            magicType: &#123;
                show: true,
                type: ['line', 'bar', 'stack', 'tiled']
            &#125;,
            restore: &#123;
                show: true
            &#125;,
            saveAsImage: &#123;
                show: true
            &#125;
        &#125;
    &#125;,
    calculable: true,
    xAxis: [&#123;
        type: 'category',
        boundaryGap: false,
        data: [' January ', ' February ', ' March ', ' April ', ' May ', ' June ', ' July ', ' August ', ' September ', ' October ', ' November ', ' December '],
        axisLabel: &#123;
            formatter: '&#123;value&#125;',
            textStyle: &#123;
                color: '#929298'
            &#125;
        &#125;
    &#125;],
    yAxis: [&#123;
        type: 'value',
        axisLabel: &#123;
            formatter: '&#123;value&#125;',
            textStyle: &#123;
                color: '#929298'
            &#125;
        &#125;,
        axisTick: &#123;
            show: true
          &#125;,
        axisLine: &#123;
            show: true,
            lineStyle: &#123;
              color: '#4c4948'&#125;
            &#125;
    &#125;],
    series: [&#123;
        name: '2020 Annual visits ',
        type: 'line',
        stack: ' Total amount ',
        data: [$&#123;monthValueArr["2020"]&#125;],
        axisLabel: &#123;
            formatter: '&#123;value&#125;',
            // The data sequence corresponding to the first year corresponds to the month 
            textStyle: &#123;
                color: '#929298'
            &#125;
        &#125;
    &#125;,
    &#123;
        name: '2021 Annual visits ',
        type: 'line',
        stack: ' Total amount ',
        data: [$&#123;monthValueArr["2021"]&#125;],
        // The data sequence corresponding to the second year corresponds to the month 
        axisLabel: &#123;
            formatter: '&#123;value&#125;',
            textStyle: &#123;
                color: '#929298'
            &#125;
        &#125;
    &#125;]
&#125;;
        pvChart.setOption(pvOption);
        window.addEventListener("resize", () => &#123; 
            pvChart.resize();
        &#125;);`
        document.getElementById('pv_container').after(script);
    &#125;).catch(function (error) &#123;
        console.log(error);
    &#125;);
&#125;
// Number of visitors 
function uvChart () &#123; 
    let script = document.createElement("script")
    fetch('/census/data/uv.json?date'+new Date()).then(data => data.json()).then(data => &#123;
        let date = new Date();
        let monthValueArr = &#123;&#125;;
        let monthName = data.result.items[0];
        let monthValue = data.result.items[1];
        for (let i =2020; i <= date.getFullYear(); i++)   monthValueArr[String(i)] = [ ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ];
        monthValueArr
        for (let i = 0; i < monthName.length; i++) &#123;
            let year = get_year(monthName[i][0]);
            let month = get_month(monthName[i][0]);
            monthValueArr[String(year)][String(month-1)] = monthValue[i][0];
        &#125;
        script.innerHTML = `
        var uvChart = echarts.init(document.getElementById('uv_container'), 'light');
        var uvOption = &#123;
    color: ['#d223e7', '#3F77FE', '#01C2F9', '#18D070'],
    title: &#123;
        text: ' Statistics of site visitors ',
        subtext: ' Data sources :  Baidu statistics ( since  2020/11/14  Start Statistics )',
        textStyle: &#123;
            color: '#504b4d',
        &#125;
    &#125;,
    tooltip: &#123;
        trigger: 'axis'
    &#125;,
    legend: &#123;
        data: ['2020 Number of annual visitors ', '2021 Number of annual visitors '],
        bottom: 0,
        left: 'center',
        textStyle: &#123;
            color: '#504b4d',
        &#125;
    &#125;,
    // Revision year 
    toolbox: &#123;
        show: true,
        feature: &#123;
            mark: &#123;
                show: true
            &#125;,
            magicType: &#123;
                show: true,
                type: ['line', 'bar', 'stack', 'tiled']
            &#125;,
            restore: &#123;
                show: true
            &#125;,
            saveAsImage: &#123;
                show: true
            &#125;
        &#125;
    &#125;,
    calculable: true,
    xAxis: [&#123;
        type: 'category',
        boundaryGap: false,
        data: [' January ', ' February ', ' March ', ' April ', ' May ', ' June ', ' July ', ' August ', ' September ', ' October ', ' November ', ' December '],
        axisLabel: &#123;
            formatter: '&#123;value&#125;',
            textStyle: &#123;
                color: '#929298'
            &#125;
        &#125;
    &#125;],
    yAxis: [&#123;
        type: 'value',
        axisLabel: &#123;
            formatter: '&#123;value&#125;',
            textStyle: &#123;
                color: '#929298'
            &#125;
        &#125;,
        axisTick: &#123;
            show: true
          &#125;,
        axisLine: &#123;
            show: true,
            lineStyle: &#123;
              color: '#4c4948'&#125;
            &#125;
    &#125;],
    series: [&#123;
        name: '2020 Number of annual visitors ',
        type: 'line',
        smooth: true,
        itemStyle: &#123;
            normal: &#123;
                areaStyle: &#123;
                    type: 'default'
                &#125;
            &#125;
        &#125;,
        data: [$&#123;monthValueArr["2020"]&#125;],
        // The data sequence corresponding to the first year corresponds to the month 
        axisLabel: &#123;
            formatter: '&#123;value&#125;',
            textStyle: &#123;
                color: '#929298'
            &#125;
        &#125;,
    &#125;,
    &#123;
        name: '2021 Number of annual visitors ',
        type: 'line',
        smooth: true,
        itemStyle: &#123;
            normal: &#123;
                areaStyle: &#123;
                    type: 'default'
                &#125;
            &#125;
        &#125;,
        data: [$&#123;monthValueArr["2021"]&#125;],
        // The data sequence corresponding to the second year corresponds to the month 
        axisLabel: &#123;
            formatter: '&#123;value&#125;',
            textStyle: &#123;
                color: '#929298'
            &#125;
        &#125;,
    &#125;]
&#125;;
        uvChart.setOption(uvOption);
        window.addEventListener("resize", () => &#123; 
            uvChart.resize();
        &#125;);`
        document.getElementById('uv_container').after(script);
    &#125;).catch(function (error) &#123;
        console.log(error);
    &#125;);
&#125;
//  Access map 
function mapChart () &#123;
    let script = document.createElement("script")
    fetch('/census/data/map.json?date'+new Date()).then(data => data.json()).then(data => &#123;
        let mapName = data.result.items[0]
        let mapValue = data.result.items[1]
        let mapArr = []
        let max = mapValue[0][0]
        for (let i = 0; i < mapName.length; i++) &#123;
            mapArr.push(&#123; name: mapName[i][0].name, value: mapValue[i][0] &#125;)
        &#125;
        let mapArrJson = JSON.stringify(mapArr)
        script.innerHTML = `
        var mapChart = echarts.init(document.getElementById('map_container'), 'light');
        var mapOption = &#123;
            title: &#123; text: ' Visit location ' &#125;,
            tooltip: &#123; trigger: 'item' &#125;,
            visualMap: &#123;
                min: 0,
                max: $&#123;max&#125;,
                left: 'left',
                top: 'bottom',
                text: [' high ',' low '],
                color: ['#1E90FF', '#AAFAFA'],
                calculable: true
            &#125;,
            series: [&#123;
                name: '$&#123;metricsName&#125;',
                type: 'map',
                mapType: 'china',
                showLegendSymbol: false,
                label: &#123;
                    emphasis: &#123; show: false &#125;
                &#125;,
                itemStyle: &#123;
                    normal: &#123;
                        areaColor: 'rgba(255, 255, 255, 0.1)',
                        borderColor: '#121212'
                    &#125;,
                    emphasis: &#123; areaColor: 'gold' &#125;
                &#125;,
                data: $&#123;mapArrJson&#125;
            &#125;]
        &#125;;
        mapChart.setOption(mapOption);
        window.addEventListener("resize", () => &#123; 
            mapChart.resize();
        &#125;);`
        document.getElementById('map_container').after(script);
    &#125;).catch(function (error) &#123;
        console.log(error);
    &#125;);
&#125;
//  Source of visit 
function sourcesChart () &#123;
    let script = document.createElement("script");
    var innerHTML = '';
    var link = 0, direct = 0, search = 0;
    fetch('/census/data/sources.json?date'+new Date()).then(data => data.json()).then(data => &#123;
        let sourcesName = data.result.items[0];
        let sourcesValue = data.result.items[1];
        let sourcesArr = [];
        for (let i = 0; i < sourcesName.length; i++)
            sourcesArr.push(&#123; name: sourcesName[i][0].name, value: sourcesValue[i][0] &#125;);
        link = sourcesArr[1]['value'] ;
        search = sourcesArr[2]['value'] ;
        direct = sourcesArr[0]['value'] ;
        innerHTML += `
        var sourcesChart = echarts.init(document.getElementById('sources_container'), 'light');
        var sourcesOption = &#123;
            title:&#123;text:' Site visitor source statistics ',itemGap:20,textStyle:&#123;color:'#504b4d',&#125;&#125;,
            tooltip: &#123; trigger: 'item', formatter: '&#123;a&#125; <br/>&#123;b&#125;: &#123;c&#125; (&#123;d&#125;%)' &#125;,
            legend: &#123;
                data: [' Through ', ' Outside the chain ', ' Search for ', ' Baidu ', ' Google ', ' Bing Ying ', 'Github', ' Go to / A ten-year contract '],
                y: 'bottom'
            &#125;,
            series: [
                &#123;
                    name: ' Source details ', type: 'pie', radius: ['45%', '60%'],
                    labelLine: &#123; length: 30 &#125;,
                    label: &#123;
                        formatter: '&#123;a|&#123;a&#125;&#125;&#123;abg|&#125;\\n&#123;hr|&#125;\\n  &#123;b|&#123;b&#125;:&#125;&#123;c&#125;  &#123;per|&#123;d&#125;%&#125;  ',
                        backgroundColor: '#F6F8FC', borderColor: '#8C8D8E',
                        borderWidth: 1, borderRadius: 4,
                        rich: &#123;
                            a: &#123; color: '#6E7079', lineHeight: 22, align: 'center' &#125;,
                            hr: &#123; borderColor: '#8C8D8E', width: '100%', borderWidth: 1, height: 0 &#125;,
                            b: &#123; color: '#4C5058', fontSize: 14, fontWeight: 'bold', lineHeight: 33 &#125;,
                            per: &#123; color: '#fff', backgroundColor: '#4C5058', padding: [3, 4], borderRadius: 4 &#125;
                        &#125;
                    &#125;,
                    data: [`;
    &#125;).catch(function (error) &#123;
        console.log(error);
    &#125;);
    fetch('/census/data/engine.json?date'+new Date()).then(data => data.json()).then(data => &#123;
        let enginesName = data.result.items[0];
        let enginesValue = data.result.items[1];
        let enginesArr = [];
        for (let i = 0; i < enginesName.length; i++)
            enginesArr.push(&#123; name: enginesName[i][0].name, value: enginesValue[i][0] &#125;);
        innerHTML += `
                        &#123;value: $&#123;enginesArr[1]['value']&#125;, name: ' Google '&#125;,
                        &#123;value: $&#123;enginesArr[0]['value']&#125;, name: ' Baidu '&#125;,`;
    &#125;).catch(function (error) &#123;
        console.log(error);
    &#125;);
    fetch('/census/data/link.json?date'+new Date()).then(data => data.json()).then(data => &#123;
        let linksName = data.result.items[0];
        let linksValue = data.result.items[1];
        let linksArr = &#123;&#125;;
        for (let i = 0; i < linksName.length; i++)
            linksArr[linksName[i][0].name] = linksValue[i][0];
        let sum = data.result.sum[0][0];
        let bing = linksArr['http://cn.bing.com']+linksArr['http://www.bing.com'];
        let github = linksArr['http://github.com'];
        innerHTML += `
                        &#123;value: $&#123;bing&#125;, name: ' Bing Ying '&#125;,
                        &#123;value: $&#123;direct&#125;, name: ' Through '&#125;,
                        &#123;value: $&#123;github&#125;, name: 'Github'&#125;,
                        &#123;value: $&#123;sum-bing-github&#125;, name: ' Friend chain '&#125;
                    ]
                &#125;,
                &#123;
                    name: ' Source of visit ', type: 'pie', selectedMode: 'single', radius: [0, '30%'],
                    label: &#123; position: 'inner', fontSize: 14&#125;,
                    labelLine: &#123; show: false &#125;,
                    data: [
                        &#123;value: $&#123;search+bing&#125;, name: ' Search for ', itemStyle: &#123; color : 'green' &#125;&#125;,
                        &#123;value: $&#123;direct&#125;, name: ' Through ', itemStyle: &#123; color : '#FFDB5C' &#125;&#125;,
                        &#123;value: $&#123;link-bing&#125;, name: ' Outside the chain ', itemStyle: &#123; color : '#32C5E9' &#125;&#125;
                    ]
                &#125;,
            ]
        &#125;;
        sourcesChart.setOption(sourcesOption);
        window.addEventListener("resize", () => &#123; 
            sourcesChart.resize();
        &#125;);`;
        script.innerHTML = innerHTML;
    &#125;).catch(function (error) &#123;
        console.log(error);
    &#125;);
    document.getElementById('sources_container').after(script);
&#125;
if (document.getElementById("calendar_container"))   calChart();
if (document.getElementById('map_container'))   mapChart();
if (document.getElementById('uv_container'))   uvChart();
if (document.getElementById('pv_container'))   pvChart();
if (document.getElementById('sources_container'))   sourcesChart();

Skip rendering because census.js stay source Folder will be rendered , Such as > Will be rendered as gt. At the site yml in skip_render: Add skip rendering items as follows :

yaml

skip_render:
  - 'census/census.js'
  - 'census/data/**'

In the theme yml There is no need to add navigation in , At this point, you can pass hexo s Local preview view .

To configure GitHub Action

blog (repository)
└── .github
    └── workflows
        └── getdata.yml

Create a new one according to the above directory getdata.yml If you've finished GitHubactions Integrated deployment . Write the following :

yaml

name:  Get Baidu Statistics 
on:
  schedule:
    - cron: '    0 0,6,12,18 * * *'
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name:  Check the branch 
        uses: actions/[email protected]
        with:
          ref: main #2020 year 10 After month github The default branch of the new warehouse is changed to main, Pay attention to change 
      - name: Set up Python # install python
        uses: actions/[email protected]
        with:
          python-version: 3.8
      - name:  get data 
        run: |
          cd /home/runner/work/hexo/hexo/source/census/data/
          pip install requests 
          python get.py
          cd /home/runner/work/hexo/hexo
          git config --global user.name " Yours GitHub The user name is like mine brqs"
          git config --global user.email " Yours GitHub Mailbox such as [email protected]"
git add .
git commit -m " Baidu statistics upload "
git push origin main

Upload to the warehouse , I set it to automatically execute every six hours. You can also reduce the frequency

原网站

版权声明
本文为[Qwe7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202090912160443.html