gpt4 book ai didi

<...> 之间的 C 条 html

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:30 24 4
gpt4 key购买 nike

如何使用 C 从 HTML 文档中的 <...> 标记之间去除 HTML?我当前的程序使用 curl 获取网页内容并将其放入文本文件,然后从文本文件中读取并删除 <>,但我不确定如何删除这些标签之间的所有内容。

#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define WEBPAGE_URL "http://homepages.paradise.net.nz/adrianfu/index.html"
#define DESTINATION_FILE "/home/user/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);

int i, nRead, fd;
int source;
char buf[1024];


if((fd = open("data.txt", O_RDONLY)) == -1)
{
printf("Cannot open the file");
}
else
{
nRead = read(fd, buf, 1024);
printf("Original String ");
for(i=0; i<nRead; i++)
{
printf("%c", buf[i]);
}

printf("\nReplaced String ");

for(i=0; i<nRead; i++)
{
if(buf[i]=='<' || buf[i]=='>'){
buf[i]=' ';

}
printf("%c", buf[i]);
}
}
close(source);

return 0;
}

最佳答案

仅放置删除“<”和“>”标签之间内容的代码(假设您处理正确的 html,这意味着您没有将一个标签嵌套在另一个标签的声明中,例如 <html < body> > ).我只是更改一小部分代码。我还将删除 buf 中的标签变量,而不是用间隔替换不需要的字符,因为我认为这对你更有用(如果我错了请纠正我)。

int idx = 0;
int opened = 0; // false
for(i=0; i<nRead; i++)
{
if(buf[i]=='<') {
opened = 1; // true
} else if (buf[i] == '>') {
opened = 0; // false
} else if (!opened) {
buf[idx++] = buf[i];
}
}
buf[idx] = '\0';
printf("%s\n", buf);

关于<...> 之间的 C 条 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9444200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com