您的位置:首页 > 理论基础 > 计算机网络

Linux企业级项目实践之网络爬虫(29)——遵守robots.txt

2014-09-04 00:27 295 查看
Robots协议(也称为爬虫协议、机器人协议等)的全称是“网络爬虫排除标准”(Robots Exclusion Protocol),网站通过Robots协议告诉搜索引擎哪些页面可以抓取,哪些页面不能抓取。

robots.txt文件是一个文本文件。robots.txt是搜索引擎中访问网站的时候要查看的第一个文件。robots.txt文件告诉蜘蛛程序在服务器上什么文件是可以被查看的。

当一个搜索蜘蛛访问一个站点时,它会首先检查该站点根目录下是否存在robots.txt,如果存在,搜索机器人就会按照该文件中的内容来确定访问的范围;如果该文件不存在,所有的搜索蜘蛛将能够访问网站上所有没有被口令保护的页面。百度官方建议,仅当您的网站包含不希望被搜索引擎收录的内容时,才需要使用robots.txt文件。如果您希望搜索引擎收录网站上所有内容,请勿建立robots.txt文件。

如果将网站视为酒店里的一个房间,robots.txt就是主人在房间门口悬挂的“请勿打扰”或“欢迎打扫”的提示牌。这个文件告诉来访的搜索引擎哪些房间可以进入和参观,哪些房间因为存放贵重物品,或可能涉及住户及访客的隐私而不对搜索引擎开放。但robots.txt不是命令,也不是防火墙,如同守门人无法阻止窃贼等恶意闯入者。

Robots协议用来告知搜索引擎哪些页面能被抓取,哪些页面不能被抓取;可以屏蔽一些网站中比较大的文件,如:图片,音乐,视频等,节省服务器带宽;可以屏蔽站点的一些死链接。方便搜索引擎抓取网站内容;设置网站地图连接,方便引导蜘蛛爬取页面。

文件写法

User-agent: * 这里的*代表的所有的搜索引擎种类,*是一个通配符

Disallow: /admin/ 这里定义是禁止爬寻admin目录下面的目录

Disallow: /require/ 这里定义是禁止爬寻require目录下面的目录

Disallow: /ABC/ 这里定义是禁止爬寻ABC目录下面的目录

Disallow: /cgi-bin/*.htm 禁止访问/cgi-bin/目录下的所有以".htm"为后缀的URL(包含子目录)。

Disallow: /*?* 禁止访问网站中所有包含问号(?) 的网址

Disallow: /.jpg$ 禁止抓取网页所有的.jpg格式的图片

Disallow:/ab/adc.html 禁止爬取ab文件夹下面的adc.html文件。

Allow: /cgi-bin/ 这里定义是允许爬寻cgi-bin目录下面的目录

Allow: /tmp 这里定义是允许爬寻tmp的整个目录

Allow: .htm$ 仅允许访问以".htm"为后缀的URL。

Allow: .gif$ 允许抓取网页和gif格式图片

Sitemap: 网站地图 告诉爬虫这个页面是网站地图

//解析robots文本
void parseRobots()
{
char key [32];
char value [100];
int i,j;
int posl = 0, posm = 0 ,posr =0;
int len = strlen(robotstxt);
bool hasAgent = false;

while(posl<len && posm<len && posr<len)
{
//找到第一个不为空格和换行符的字符位置,确定posl
while(posl<len && (robotstxt[posl]==' '
|| robotstxt[posl]=='\n' ||robotstxt[posl]=='\r')) posl++;
//以#开头的,直接过滤掉该行
if(robotstxt[posl]=='#')
{
while(posl<len && robotstxt[posl]!='\n') posl++;
continue;
}
//找‘:’,确定posm
posm = posl+1;
while(posm<len && robotstxt[posm]!=':') posm++;
//找换行符位置,确定posr
posr = posm+1;
while(posr<len && robotstxt[posr]!='\n') posr++;

for(j=0,i=posl;i<posm;i++)
{
if(robotstxt[i]!=''&&robotstxt[i]!='\t'&&robotstxt[i]!='\r'&&robotstxt[i]!='\n')
key[j++] = robotstxt[i];
}
key[j] = '\0';
for(j=0,i=posm+1;i<posr;i++)
{
if(robotstxt[i]!=''&&robotstxt[i]!='\t'&&robotstxt[i]!='\r'&&robotstxt[i]!='\n')
value[j++] = robotstxt[i];
}
value[j]='\0';
posl = posr;

if(strcmp(strlwr(key),"user-agent")==0){
if(strcmp(value,"*")==0||strcmp(value,"webcrawler")==0)
{
hasAgent = true;
}
else hasAgent = false;
}
if(hasAgent)
{
int len_val = strlen(value);
if(len_val<=0) continue;
if(strcmp(strlwr(key),"disallow")==0 &&disallow_size<MAXDISALLOW)
{
disallow[disallow_size] = newchar [len_val+1];
strcpy(disallow[disallow_size],strlwr(value));
disallow_size++;
}
else if (strcmp(strlwr(key),"allow")==0 &&allow_size<MAXDISALLOW)
{
allow[allow_size] = new char[len_val+1];
strcpy(allow[allow_size],strlwr(value));
allow_size++;
}
else if(strcmp(strlwr(key),"craw-delay")==0)
{
crawldelay = 0;
int len_val = strlen(value);
for(int i=0;i<len_val;i++)
{
crawldelay = crawldelay *10 + value[i]-'0';
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: