c - 从缓冲区 C 读取

标签 c linux curl libcurl

我正在尝试创建一个简单的 c 程序,从网页中剥离 HTML 并保留文本。到目前为止,我已经想出了下面的代码。它使用 cURL 获取网页内容并将其写入文件。我如何遍历内存缓冲区并删除所有 HTML 标记并将文本输出到终端或文件?

#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
#define WEBPAGE_URL "http://homepages.paradise.net.nz/adrianfu/index.html"
#define DESTINATION_FILE "/home/acwest/data.txt"

size_t write_data( void *ptr, size_t size, size_t nmeb, void *stream)
{
 return fwrite(ptr,size,nmeb,stream);
}

int main()
{
 int in_tag = 0;
 char * buffer;
 char c;
 long lSize;
 size_t result;

 FILE * file = fopen(DESTINATION_FILE,"w+");
 if (file==NULL) {
fputs ("File error",stderr); 
exit (1);
}

 CURL *handle = curl_easy_init();
 curl_easy_setopt(handle,CURLOPT_URL,WEBPAGE_URL); /*Using the http protocol*/
 curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION, write_data);
 curl_easy_setopt(handle,CURLOPT_WRITEDATA, file);
 curl_easy_perform(handle);
 curl_easy_cleanup(handle);

 // obtain file size:
 fseek (file, 0, SEEK_END);
 lSize = ftell (file);
 rewind (file);

 // allocate memory to contain the whole file:
 buffer = (char*) malloc (sizeof(char)*lSize);
 if (buffer == NULL) {
fputs ("Memory error",stderr); 
exit (2);
}

 // copy the file into the buffer:
 result = fread (buffer,1,lSize,file);
 if (result != lSize) {
fputs ("Reading error",stderr); 
exit (3);
}
}

最佳答案

Curl 不会帮助您解析 HTML,而且这是一项复杂的任务。您可以阅读语言规范并编写解析器。 http://www.mbayer.de/html2text/ 有一个开源 C++ 项目或 https://github.com/aaronsw/html2text 处的 python 脚本.您还可以从命令行安装和使用 html2text 或从您的 C 代码执行它。

关于c - 从缓冲区 C 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9443327/

相关文章:

php - 以编程方式更改 to 退出节点(获取新 IP)

curl - 将命令行 cURL 转换为 C cURL

c - 使用 xsltproc 将 XML 转为 postscript

c++ - "atomic object"的定义

c - avformat_write_header 失败并出现错误“无效参数

c - 模拟 UNIX 类型的 shell

c - 无法理解以下程序中的 pthread_create() 行为?

php - 将数据写入具有 777 权限的文件

Linux Bash Number Range echo 语法错误

php - Paypal IPN curl 问题