Robots.txt 协议—百度之星

来源:互联网 发布:大数据的主要特征 编辑:程序博客网 时间:2024/04/29 16:09

题目描述

搜 索引擎是靠 Web Robot (又称 Spider )来收集互联网上浩如烟海的网页的。 Spider 就像一个旅行家一般,不知疲倦地奔波于万维网的空间,将遇到的页面收集下来供搜索引擎索引。对于一个网站的管理员来说,如果希望搜索引擎只收录自己指定的 内容,或者指定某些不希望搜索引擎访问的内容,该如何去做呢?他需要的就是 Robots Exclusion Protocol 协议,这里简单的称它做 Robots.txt 协议。

Robots.txt 是一个放置在网站根目录下的纯文本文件。举例来说,当 Spider 访问一个网站(比如 http://www.example.com )时,首先会检查该网站中是否存在 http://www. example.com/robots.txt 这个文件,如果 Spider 找到这个文件,它就会根据这个文件的内容,来确定它访问权限的范围。

www.robotstxt.org 是 robots.txt 协议的 Home Page ,在这个站点上你可以找到很多 robots.txt 协议相关的资料。 Robots.txt 协议在 http://www.robotstxt.org/wc/norobots.html 上有比较详尽的描述。

你的任务就是编写 Spider 中的一个逻辑单元,这个单元的作用就是来判断一个网站的一些 URL 是否被禁止抓取。对方网站的站点在这里假设是 www.example.com , 这个 Spider 的 User-agent 当然是 Baiduspider 。注意,这个逻辑单元除了本身的判断逻辑要求与 robots.txt 协议一致外,还要注意容错的问题。互联网上纷繁芜杂,会出现很多意想不到的错误。如何能够对一个对错参半的 robots.txt 进行解析,把其中正确的挑拣出来、把错误的部分忽略掉,也是一个不小的挑战哦。都会遇到什么错误?在开始爬行互联网之前,谁都不知道。

 

输入格式

第一行是一个正整数 m ,表示 robots.txt 文件的行数,后面跟 m 行,是 robots.txt 的全文。下一行包含一个正整数 n , 表示 URL 的行数,后面跟 n 行 URL ,这个就是你要判断的 URL 的列表。

 

输出格式

每条 URL 输出一行,每行两列,第一列是一个数字,如果这条 URL 被禁止,则输出 0 ,否则输出 1 。第二列是这条 URL 本身。

 

输入样例

2

User-agent: *

Disallow: /tmp/

2

http://www.example.com/index.html

http://www.example.com/tmp/somepage.html

 

输出样例

1 http://www.example.com/index.html

0 http://www.example.com/tmp/somepage.html

 

评分方法

本题包含 20 组数据,均满足 0<=n,m<=100 。

 

 

这个题看上去简单,但是不容易考虑周全,robots.txt中可能有很多陷阱,当然我也没有心思去考虑周全,本来开始是读取文件的,后来认真读题发现是标准输入,又改了下,大致程序如下,只对正确的格式作出判断,有错误的地方以及多个robots就没办法了:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>

using namespace std;

int main(int argc, char *argv[])
{
    string s = "\n";
    vector<string> v;
    //ifstream fin("Robots.txt");

    int i;
    cin>>i;
    string first, second;
    int count = 0;
    while (count<i)
    {
        cin>>first>>second;
        if (first.find("Disallow")==0)
        {
            v.push_back(second);
            //cout<<"disallow: "<<word<<endl;
        }
        getline(cin, s);
        //cout<<s<<endl;
        count++;
    }
    count = 0;
    cin>>i;
    //cout<<i<<endl;
    vector<string> hv;
    string http;
    while (count<i)
    {
        cin>>http;
        hv.push_back(http);
        count++;
    }
    for (vector<string>::iterator h=hv.begin();h!=hv.end();++h )
    {
        int b = 1;
        for(vector<string>::iterator i=v.begin();i!=v.end();++i)
        {
            if((*h).find(*i)!=string::npos)
            {
                b = 0;
                break;
            }
        }
        cout<<b<<" "<<*h<<endl;
    }
   
       
       
    return 0;
}

对于如下的简单robots是没有问题的:

2
User-agent: *
Disallow: /tmp/
5
http://www.example.com/index.html
http://www.example.com/tmp/somepage.html
http://www.example.com/index.html
http://www.example.com/tmp/somepage.html
http://www.example.com/index.html

原创粉丝点击