您的位置:首页 > 编程语言 > C语言/C++

简单网页爬虫

2016-09-08 19:48 309 查看
这是第一次写的爬虫,在windows平台下的VS,对象是一个旅游网站上面的图片,实现其先要对VS的数据库进行设定,然后才能运行改程序

#include<stdio.h>
#include<stdlib.h>
#include <assert.h>
#include <string.h>
#include <Urlmon.h>

void loding_html_first();
void loding_html_second();
void loding_picture();
//三次下载,第一次下载的是354页的页面,第二次下载的是每张图片点进去的页面,在此页面中下载图片

#define PAGE_NUM 4
int main()
{
loding_html_first();
loding_html_second();
loding_picture();
return 0;
}

void loding_html_first()  //http://chanyouji.com/?page=1
{
char url_head[100] = "http://chanyouji.com/?page=";
char file[100] = {0};
char url[256] = {0};
for(int i=1; i<=PAGE_NUM; i++)
{
sprintf(file, "D:\\电影\\gg\\%d.html", i);  //文件名 //url字符串后面有一个字符串结束符,则该函数是将后面的数字覆盖了前面的结束符。
sprintf(url, "%s%d", url_head, i);
URLDownloadToFile(NULL, url, file, 0, NULL);
}
}

void loding_html_second()  //http://chanyouji.com/trips/547391
{
char file_name[128];
for(int i=1; i<=PAGE_NUM ;i++)    //共有354页,1.html
{
sprintf(file_name, "D:\\电影\\gg\\%d.html", i);
FILE *fr = fopen(file_name, "r");
assert(fr != NULL);
//Evaluates an expression and when the result is FALSE, prints a diagnostic message and aborts the program.

fseek(fr, 0, SEEK_END);
int file_lenth = ftell(fr);
rewind(fr);

char *temp = (char *)malloc(sizeof(char)*file_lenth+10);
fread(temp, sizeof(char), file_lenth, fr);
fclose(fr);

//寻找第二次下载所需要的目标
char new_url[256];
char *point=temp;
char num[10] = {0};
char file_nam[128];

while((point = strstr(point,"/trips/")) != NULL)   //将该字符后的六位拿出来
{
point = point+strlen("/trips/");
strncpy(num, point, 6);
sprintf(new_url,"%s%s","http://chanyouji.com/trips/",num);
printf("%s",new_url);
sprintf(file_name,"D:\\电影\\hh\\%d.html",i);//将文件存入电脑
URLDownloadToFile(NULL,new_url,file_name,0,NULL);
point+=6;
}
free(temp);
}
}

void loding_picture()
{
char file_name1[128];
FILE *fr;
int i = 1;
int m = 1;
while(sprintf(file_name1,"D:\\电影\\hh\\%d.html",i), fr=fopen(file_name1,"r"))
{
fseek(fr, 0, SEEK_END);
int file_lenth = ftell(fr);
rewind(fr);

char *ptr = (char *)malloc(sizeof(char)*file_lenth+10);
assert(ptr != NULL);

fread(ptr, sizeof(char), file_lenth, fr);
fclose(fr);

char *pt = ptr;
char buffer[256];
char file_name2[128] = {0};

while((pt=strstr(pt,"http://p.chanyouji.cn/")) != NULL)
{
strncpy(buffer,pt,256);//对该字符串进行截断操作
buffer[255]=0;
char *p = strstr(buffer,".jpg");
if(p != NULL)
{
*(p+strlen(".jpg"))=0;
sprintf(file_name2,"D:\\电影\\mm\\%d.jpg",m);//将文件存入电脑
printf("%s", buffer);
URLDownloadToFile(NULL, buffer, file_name2, 0, NULL);
}
else
{
continue;
}
++m;
pt+=strlen("http://p.chanyouji.cn/");
}
free(ptr);
++i;
}
if(fr==NULL)
{
printf("open error");
exit(1);
}
}

每个网页都有一个URL,找到该URL调用函数访问该点进行下载,下载下来该网页的内容,将其HTML文件包进行逐个字符检查,找出有用的数据进行存储或者下载图片等。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程 c语言 爬虫