用C++写一个爬取图片的爬虫的代码
时间: 2023-04-04 19:02:27 浏览: 77
您好,以下是用 C 语言编写的爬取图片的爬虫代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#define MAX_URL_LEN 1024
#define MAX_FILENAME_LEN 256
// 回调函数,将下载的图片保存到本地文件中
size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) {
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
int main() {
CURL *curl;
CURLcode res;
char url[MAX_URL_LEN];
char filename[MAX_FILENAME_LEN];
FILE *fp;
// 输入要爬取的图片链接
printf("请输入要爬取的图片链接:");
scanf("%s", url);
// 初始化 curl
curl = curl_easy_init();
if (curl) {
// 设置要下载的图片链接
curl_easy_setopt(curl, CURLOPT_URL, url);
// 获取文件名
char *p = strrchr(url, '/');
if (p) {
strcpy(filename, p + 1);
} else {
strcpy(filename, "image.jpg");
}
// 打开文件
fp = fopen(filename, "wb");
if (fp == NULL) {
printf("无法打开文件 %s\n", filename);
return 1;
}
// 设置回调函数
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
// 执行下载
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("下载失败:%s\n", curl_easy_strerror(res));
} else {
printf("下载成功,已保存到文件 %s\n", filename);
}
// 关闭文件
fclose(fp);
// 清理 curl
curl_easy_cleanup(curl);
}
return 0;
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)