详解Django的 get_meta_robots() 函数:获取页面的机器人指令

  • Post category:Python

get_meta_robots()函数是Django框架中的一个视图函数,用于向网页添加meta标签中的robots属性,以控制搜索引擎爬虫对网站内容的索引和收录。

使用方法:

  1. 在视图函数中引用该函数:
    from django.template import RequestContext
    from django.shortcuts import render

def my_view(request):
context = {‘page_title’: ‘My Page’}
return render(request, ‘my_template.html’, context,
context_instance=RequestContext(request))

  1. 在模板中使用该函数:
    {% load meta %}




{{ page_title }}
{% get_meta_robots as meta_robots %}
{% if meta_robots %}

{% endif %}



该函数返回的值可以为以下三种:

  1. none:表示搜索引擎可以对该网页进行索引和收录,不做任何限制。
  2. noindex:表示搜索引擎不对该网页进行索引和收录。
  3. nofollow:表示搜索引擎可以对该网页进行索引和收录,但不会对该网页中的链接进行跟踪,即不会传送链接权重。

实例说明:

  1. 某公司网站的招聘信息页面,需要限制搜索引擎对该页面的收录,使用方法:在视图函数中添加以下代码,将返回值设置为”noindex”。

from django.views.generic import TemplateView

class JobPageView(TemplateView):
template_name = “job.html”

   def get_meta_robots(self, context=None, **kwargs):
       return "noindex"

在模板的标签中使用{% get_meta_robots %}即可。

  1. 一个博客系统,需要对该网站内部的搜索引擎进行限制,避免搜索引擎爬虫把博客系统中的搜索结果包含进去造成混乱,使用方法:在模板中添加以下代码,将返回值设置为”noindex, nofollow”。

{% load meta %}




{{ page_title }}
{% get_meta_robots as meta_robots %}
{% if meta_robots %}

{% endif %}
{% block extrahead %}{% endblock %}



{% block content %}{% endblock %}


在搜索页面的视图函数中,添加以下代码:

def search(request):
q = request.GET.get(‘q’)
results = Blog.objects.filter(title__icontains=q)
return render(request, ‘blog/search_results.html’, {‘results’: results})

可以看到,该视图函数并没有设置get_meta_robots属性,因此默认使用了模板中设置的”noindex, nofollow”。