C語言調用curl庫抓取網頁圖片(轉)

來源:互聯網
上載者:User

標籤:ini   code   malloc   open   ring   思路   curl   file   key   

思路是先用curl抓取網頁源碼,然後以關鍵字尋找出圖片網址。

 範例:
 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <curl/curl.h> 5   6 void get_key_from_str(char *origin, char *str1, char *str2, char *key); 7   8 int main(int argc, char **argv) 9 {10     CURL *curl;11     FILE *fp = NULL, *fp_read = NULL;12     int file_size = 0;13     char *tmp = NULL;14     int flag = 0;15     char key[1024] = {0};16     char str1[128] = {0};17     char str2[128] = {0};18 19     if ((fp = fopen("test.txt", "w")) == NULL)20     {21         return 1;22     }23     curl = curl_easy_init();24     if (curl)25     {26         flag = 1;27         curl_easy_setopt(curl, CURLOPT_URL, argv[1]);     //curl設定網址28         curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);     //將網頁源碼存在檔案中,好像只能存檔案,不能存字串29         curl_easy_perform(curl);//開始抓取30         curl_easy_cleanup(curl);31         fclose(fp);32         fp_read = fopen("test.txt", "rb");33         fseek(fp_read, 0, SEEK_END);      //把指標移到文本最後34         file_size = ftell(fp_read)     ;//算出文字大小35         fseek(fp_read, 0, SEEK_SET);     //再把指標移到最前面36         tmp = (char *)malloc(file_size * sizeof(char));     //malloc一段記憶體37         printf("file_size:%d\n", file_size);38         fread(tmp, file_size, sizeof(char), fp_read);     //讀取檔案39         fclose(fp_read);40         snprintf(str1, sizeof(str1), "img src=\"");41         snprintf(str2, sizeof(str2), "\"");42         get_key_from_str(tmp, str1, str2, key);     //取得網址43  44         printf("key:%s\n", key);45         free(tmp);46     }47  48     if (!flag)49     {50         fclose(fp);51     }52  53     return 0;54 }55 //抓取str1和str2之間的關鍵字56 void get_key_from_str(char *origin, char *str1, char *str2, char *key)57 {58     char *p = strstr(origin, str1);59     char *q = strstr(p + strlen(str1), str2);60     int len = q - p - strlen(str1);61     snprintf(key, len + 1, "%s", p + strlen(str1));62     key[len + 1] = ‘\0‘;63 }


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

./test url

C語言調用curl庫抓取網頁圖片(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.