15

从0到1搭建个人网站 九-实现真实用户的pv计算

 3 years ago
source link: http://www.lcsays.com/blogshow?blogId=135
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
1501199869_flow.jpg
自己写完的文章,你需要知道哪一篇最受用户欢迎,还需要展现在自己的网站上,让用户也找到最受欢迎的那篇,统计pv要尽量避免爬虫的干扰,体现真实用户的浏览量,这里是有窍门的

请尊重原创,转载请注明来源网站www.shareditor.com以及原始链接地址

pv计算如何过滤爬虫

首先我们要理解爬虫是干什么的,爬虫是抓取你网页的内容,之后用于自己的搜索引擎或者做数据挖掘或者盗用,因此爬虫想要的其实是你的网页里的文本内容,也可能需要样式、布局等,但因为抓取效率的考虑,不会渲染里面的js,也不会抓取里面的图片链接,所以利用这一点,我们找到一个方法可以很好的过滤爬虫的干扰

创建js文件动态生成gif图片

创建web/static/web/my/pv.js,内容如下:

// 为了过滤爬虫,上报的信息是通过js渲染进行的,同时渲染出来的是个图片,这样可以过滤大部分爬虫,同时异步加载和更新pv,不影响用户体验
$(function()
{
    var gif_url = '/report/pv.gif?url=' + window.location.href;
	var report ="<img id='report_gif' src='" + gif_url + "'>";
	$("#report").html(report);
    $("#report").css('height', 0);
    $("#report").css('width', 0);
});

把这个js添加到所有网页公共的模板的head标签中,即base.html模板

<script src="{% static '/web/my/pv.js' %}"></script>

并在base.html的body中增加如下节点,这样js里动态生成gif就会放到这里:

<div id="report"></div>

下面我们创建一个1像素大小的gif文件,并放到web/static/web/images/onepixel.gif路径下

为了响应这个动态gif的浏览器请求,我们实现如下方法:

在web/views.py中添加:

import os
import re
from django.conf import settings
report_url_pattern = re.compile(r'.*blogId=(\d+).*')
def report_pv(request):
    if 'url' in request.GET:
        url = request.GET['url']
        m = re.match(report_url_pattern, url)
        if m:
            blog_id = int(m.group(1))
            blog = BlogPost.objects.get(id=blog_id)
            blog.pv = blog.pv + 1
            blog.save()
    image_data = open(os.path.join(settings.BASE_DIR, 'web/static/web/images/onepixel.gif'), "rb").read()
    return HttpResponse(image_data, content_type="image/gif")

在urls.py添加

url(r'^report/pv.gif$', views.report_pv, name='report_pv'),

好了,现在大功告成,这样我们通过浏览器访问可以正常统计到pv,而爬虫过来就不会统计上去了


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK