写一段能在网上搜集图片的C++代码
时间: 2024-02-15 17:05:26 浏览: 21
以下是一个基于libcurl库的简单示例代码,用于在百度图片搜索中搜集图片:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <curl/curl.h>
#include <regex>
using namespace std;
// 回调函数,用于处理libcurl获取到的数据
size_t write_data(void* ptr, size_t size, size_t nmemb, void* stream) {
string* str = (string*)stream;
str->append((char*)ptr, size * nmemb);
return size * nmemb;
}
// 获取图片链接
void get_image_links(string& html, vector<string>& links) {
regex reg("src=\"(http(s?):/)?/[^>]+?\\.(jpg|jpeg|png|bmp|gif)\"");
smatch match;
while (regex_search(html, match, reg)) {
links.push_back(match[0]);
html = match.suffix().str();
}
}
// 下载图片
void download_image(const string& url, const string& filename) {
CURL* curl = curl_easy_init();
if (curl) {
FILE* fp = fopen(filename.c_str(), "wb");
if (fp) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
cout << "Download failed: " << curl_easy_strerror(res) << endl;
}
fclose(fp);
}
curl_easy_cleanup(curl);
}
}
int main() {
CURL* curl = curl_easy_init();
if (curl) {
string url = "https://image.baidu.com/search/index?tn=baiduimage&word=cat";
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
string html;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &html);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
cout << "Download failed: " << curl_easy_strerror(res) << endl;
return 1;
}
vector<string> links;
get_image_links(html, links);
for (const auto& link : links) {
cout << link << endl;
string filename = link.substr(link.rfind("/") + 1);
download_image(link, filename);
}
curl_easy_cleanup(curl);
}
return 0;
}
```
这段代码实现了从百度图片搜索中下载所有与“cat”相关的图片。其中,使用了libcurl库进行网络连接和数据获取,使用了正则表达式提取图片链接,使用了文件操作函数保存下载的图片。