我正在尝试创建一个简单的 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/