帮我写一个爬取百度热搜的c++代码
时间: 2024-06-10 18:06:03 浏览: 18
好的,这是一个爬取百度热搜的 C 语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
// 定义一个结构体,用于保存网页内容
struct MemoryStruct {
char *memory;
size_t size;
};
// 回调函数,用于获取网页内容
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
// 内存分配失败
printf("Not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
int main(void) {
CURL *curl;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory = malloc(1); // 分配 1 字节的内存
chunk.size = 0; // 初始化内存大小为 0
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
// 设置 cURL 选项
curl_easy_setopt(curl, CURLOPT_URL, "http://www.baidu.com/s?wd=百度热搜");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64; rv:79.0) Gecko/20100101 Firefox/79.0");
// 执行 cURL 会话
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
// cURL 会话执行出错
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_st
相关推荐
![](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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)