C語言調用curl庫抓取網頁圖片,curl抓取
思路是先用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 = 0;
char *tmp = NULL;
int flag = 0;
char key[1024] = {0};
char str1[128] = {0};
char str2[128] = {0};
if ((fp = fopen("test.txt", "w")) == NULL)
{
return 1;
}
curl = curl_easy_init();
if (curl)
{
flag = 1;
curl_easy_setopt(curl, CURLOPT_URL, argv[1]); //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, 0, SEEK_END); //把指針移到文本最後
file_size = ftell(fp_read) ;//算出文本大小
fseek(fp_read, 0, 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 0;
}
//抓取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 + 1, "%s", p + strlen(str1));
key[len + 1] = '\0';
}
gcc -g -Wall main.c -o test -lcurl
./test url
即可