C语言调用curl库抓取网页图片(转)

时间:2021-11-20 14:53:20

思路是先用curl抓取网页源码,然后以关键字寻找出图片网址。

 范例:
 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h> void get_key_from_str(char *origin, char *str1, char *str2, char *key); int main(int argc, char **argv)
{
CURL *curl;
FILE *fp = NULL, *fp_read = NULL;
int file_size = ;
char *tmp = NULL;
int flag = ;
char key[] = {};
char str1[] = {};
char str2[] = {}; if ((fp = fopen("test.txt", "w")) == NULL)
{
return ;
}
curl = curl_easy_init();
if (curl)
{
flag = ;
curl_easy_setopt(curl, CURLOPT_URL, argv[]); //curl设置网址
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); //将网页源码存在文件中,好像只能存文件,不能存字符串
curl_easy_perform(curl);//开始抓取
curl_easy_cleanup(curl);
fclose(fp);
fp_read = fopen("test.txt", "rb");
fseek(fp_read, , SEEK_END); //把指针移到文本最后
file_size = ftell(fp_read) ;//算出文本大小
fseek(fp_read, , SEEK_SET); //再把指针移到最前面
tmp = (char *)malloc(file_size * sizeof(char)); //malloc一段内存
printf("file_size:%d\n", file_size);
fread(tmp, file_size, sizeof(char), fp_read); //读取文件
fclose(fp_read);
snprintf(str1, sizeof(str1), "img src=\"");
snprintf(str2, sizeof(str2), "\"");
get_key_from_str(tmp, str1, str2, key); //取得网址 printf("key:%s\n", key);
free(tmp);
} if (!flag)
{
fclose(fp);
} return ;
}
//抓取str1和str2之间的关键字
void get_key_from_str(char *origin, char *str1, char *str2, char *key)
{
char *p = strstr(origin, str1);
char *q = strstr(p + strlen(str1), str2);
int len = q - p - strlen(str1);
snprintf(key, len + , "%s", p + strlen(str1));
key[len + ] = '\0';
}

gcc -g -Wall main.c -o test -lcurl

./test url