码迷,mamicode.com
首页 > 编程语言 > 详细

Python网页分析,分析网站的日志数据

时间:2020-09-07 19:02:22      阅读:39      评论:0      收藏:0      [点我收藏+]

标签:page   转化   俄罗斯   plt   byte   asi   下载   time   dac   

前言

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

以下文章来源于大话数据分析,作者:尚天强

网站的日志数据记录了所有Web对服务器的访问活动,本节通过Python第三方库解析网站日志,利用pandas对网站日志数据进行预处理,并用可视化技术,对于网站日志数据进行分析。

PS:如有需要Python学习资料的小伙伴可以加下方的群去找免费管理员领取

技术图片

 

可以免费领取源码、项目实战视频、PDF文件等

技术图片

 

数据来源

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import apache_log_parser        # 首先通过 pip install apache_log_parser 安装库
%matplotlib inline
fformat = ‘%V %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %T‘  # 创建解析器
p = apache_log_parser.make_parser(fformat)
sample_string = ‘koldunov.net 85.26.235.202 - - [16/Mar/2013:00:19:43 +0400] "GET /?p=364 HTTP/1.0" 200 65237 "http://koldunov.net/?p=364" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11" 0‘
data = p(sample_string) #解析后的数据为字典结构
data
技术图片

 

datas = open(r‘H:\python数据分析\数据\apache_access_log‘).readlines()  #逐行读取log数据
log_list = []  # 逐行读取并解析为字典
for line in datas:
data = p(line)
data[‘time_received‘] = data[‘time_received‘][1:12]+‘ ‘+data[‘time_received‘][13:21]+‘ ‘+data[‘time_received‘][22:27] #时间数据整理
log_list.append(data)    #传入列表
log = pd.DataFrame(log_list)   #构造DataFrame
log = log[[‘status‘,‘response_bytes_clf‘,‘remote_host‘,‘request_first_line‘,‘time_received‘]]   #提取感兴趣的字段
log.head()
#status 状态码 response_bytes_clf 返回的字节数(流量)remote_host 远端主机IP地址 request_first_line 请求内容t ime_received 时间数据
技术图片

 

日志数据清洗

log.isnull().sum() # 查看缺失值
技术图片

 

log[‘time_received‘] = pd.to_datetime(log[‘time_received‘]) #把time_received字段转换为时间数据类型,并设置为索引
log = log.set_index(‘time_received‘)
log.head()
技术图片

 

log.dtypes # 查看类型
技术图片

 

log[‘status‘] = log[‘status‘].astype(‘int‘) # 转换为int类型
log[‘response_bytes_clf‘].unique()
array([‘26126‘, ‘10532‘, ‘1853‘, ..., ‘66386‘, ‘47413‘, ‘48212‘], dtype=object)
log[log[‘response_bytes_clf‘] == ‘-‘].head() #对response_bytes_clf字段进行转换时报错,查找原因发现其中含有“-”
技术图片

 

def dash2nan(x):    # 定义转换函数,当为“-”字符时,将其替换为空格,并将字节数据转化为M数据
   if x == ‘-‘:
x = np.nan
   else:
x = float(x)/1048576
   return x
log[‘response_bytes_clf‘] = log[‘response_bytes_clf‘].map(dash2nan)
log.head()
技术图片

 

log.dtypes
技术图片

 

 

日志数据分析

log[‘response_bytes_clf‘].plot()
技术图片

 

流量起伏不大,但有一个极大的峰值超过了20MB。

log[log[‘response_bytes_clf‘]>20] #查看流量峰值
技术图片

 

t_log = log[‘response_bytes_clf‘].resample(‘30t‘).count()
t_log.plot()

对时间重采样(30min),并计数 ,可看出每个时间段访问的次数,早上8点访问次数最多,其余时间处于上下波动中。

技术图片

 

h_log = log[‘response_bytes_clf‘].resample(‘H‘).count()
h_log.plot()

当继续转换频率到低频率时,上下波动不明显。

技术图片

 

d_log = pd.DataFrame({‘count‘:log[‘response_bytes_clf‘].resample(‘10t‘).count(),‘sum‘:log[‘response_bytes_clf‘].resample(‘10t‘).sum()})    
d_log.head()
技术图片

 

构造访问次数和访问流量的 DataFrame。

plt.figure(figsize=(10,6))   #设置图表大小
ax1 = plt.subplot(111)    #一个subplot
ax2 = ax1.twinx()     #公用x轴
ax1.plot(d_log[‘count‘],color=‘r‘,label=‘count‘)
ax1.legend(loc=2)
ax2.plot(d_log[‘sum‘],label=‘sum‘)
ax2.legend(loc=0)
技术图片

 

绘制折线图,有图可看出,访问次数与访问流量存在相关性。

IP地址分析

ip_count = log[‘remote_host‘].value_counts()[0:10] #对remote_host计数,并取前10位
ip_count
技术图片

 

ip_count.plot(kind=‘barh‘) #IP前十位柱状图
技术图片

 

import pygeoip # pip install pygeoip 安装库
# 同时需要在网站上(http://dev.maxmind.com/geoip/legacy/geolite)下载DAT文件才能解析IP地址
gi = pygeoip.GeoIP(r‘H:\python数据分析\数据\GeoLiteCity.dat‘, pygeoip.MEMORY_CACHE)
info = gi.record_by_addr(‘64.233.161.99‘)
info #解析IP地址
技术图片

 

ips = log.groupby(‘remote_host‘)[‘status‘].agg([‘count‘]) # 对IP地址分组统计
ips.head()
技术图片

 

ips.drop(‘91.224.246.183‘,inplace=True)

ips[‘country‘] = [gi.record_by_addr(i)[‘country_code3‘] for i in ips.index] # 将IP解析的国家和经纬度写入DataFrame
ips[‘latitude‘] = [gi.record_by_addr(i)[‘latitude‘] for i in ips.index]
ips[‘longitude‘] = [gi.record_by_addr(i)[‘longitude‘] for i in ips.index]

ips.head()
技术图片

 

country = ips.groupby(‘country‘)[‘count‘].sum() #对country字段分组统计
country = country.sort_values(ascending=False)[0:10] # 筛选出前10位的国家
country
技术图片

 

country.plot(kind=‘bar‘)
技术图片

 

俄罗斯的访问量最多,可推断该网站来源于俄罗斯。

from mpl_toolkits.basemap import Basemap

plt.style.use(‘ggplot‘)
plt.figure(figsize=(10,6))

map1 = Basemap(projection=‘robin‘, lat_0=39.9, lon_0=116.3,
resolution = ‘l‘, area_thresh = 1000.0)

map1.drawcoastlines()
map1.drawcountries()
map1.drawmapboundary()

map1.drawmeridians(np.arange(0, 360, 30))
map1.drawparallels(np.arange(-90, 90, 30))

size = 0.03
for lon, lat, mag in zip(list(ips[‘longitude‘]), list(ips[‘latitude‘]), list(ips[‘count‘])):
x,y = map1(lon, lat)
msize = mag * size
map1.plot(x, y, ‘ro‘, markersize=msize)
技术图片

Python网页分析,分析网站的日志数据

标签:page   转化   俄罗斯   plt   byte   asi   下载   time   dac   

原文地址:https://www.cnblogs.com/hhh188764/p/13574245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!