[英]How to create a html tree?
我需要在一些html文件中進行一些挖掘,我想首先將它們轉換為一行中一個標簽的樹的可讀形式。 不過,我沒有html的經驗。 有人可以改正我的代碼並指出我忘記的規則嗎?
我的代碼不適用於現實生活中的頁面。 在程序執行結束時,嵌套計數器應設置為0,因為程序應保留其已遇到的所有嵌套標記。 它不是。 對於一個Facebook頁面,有超過2000個標簽保持打開狀態。
在有人建議我使用圖書館之前,我還沒有看到任何好的圖書館。 對於我的頁面,以某種方式轉換為xml失敗,並且htmlcxx庫沒有適當的文檔。
#include <cstdio>
char get_char( FILE *stream ) {
char c;
do
c = getc(stream);
while ( c == ' ' || c == '\n' || c == '\t' || c == '\r' );
return c;
}
void fun( FILE *stream, FILE *out ) {
int counter = -1;
char c;
do {
c = get_char(stream);
if ( c == EOF )
break;
if ( c != '<' ) { // print text
for ( int i = counter + 1; i; --i )
putc( ' ', out );
fprintf( out, "TEXT: " );
do {
if ( c == '\n' )
fprintf( out, "<BR>" ); // random separator
else
putc( c, out );
c = getc( stream );
} while ( c != '<' );
putc( '\n', out );
}
c = getc( stream );
if ( c != '/' ) { // nest deeper
++counter;
for ( int i = counter; i; --i )
putc( ' ', out );
} else { // go back in nesting
--counter;
// maybe here should be some exception handling
do // assuming there's no strings in quotation marks here
c = getc( stream );
while ( c != '>' );
continue;
}
ungetc( c, stream );
do { // reading tag
c = getc(stream);
if( c == '/' ) { // checking if it's not a <blahblah/>
c = getc(stream);
if ( c == '>' ) {
--counter;
break;
}
putc( '/', out );
putc( c, out );
} else if ( c == '"' ) { // not parsing strings put in quotation marks
do {
putc( c, out ); c = getc( stream );
if ( c == '\\' ) {
putc( c, out ); c = getc( stream );
if ( c == '"' ) {
putc( c, out ); c = getc( stream );
}
}
} while ( c != '"' );
putc( c, out );
} else if ( c == '>' ) { // end of tag
break;
} else // standard procedure
putc( c, out );
} while ( true );
putc( '\n', out );
} while (true);
fprintf( out, "Counter: %d", counter );
}
int main() {
const char *name = "rfb.html";
const char *oname = "out.txt";
FILE *file = fopen(name, "r");
FILE *out = fopen(oname, "w");
fun( file, out );
return 0;
}
HTML!= XML標記可以不關閉,例如<img ...>
被認為等於<img ... />
這樣有趣而有用的話題,幾乎沒有答案。 真的很奇怪
很難找到好的C ++ HTML解析器! 我會嘗試引導正確的方向...這可能會幫助您繼續前進...
Lib curl頁面上有一些源代碼可以助您一臂之力。 遍歷dom樹的文檔。 您不需要xml解析器。 在格式錯誤的html上不會失敗。
http://curl.haxx.se/libcurl/c/htmltidy.html
另一個選項是htmlcxx。 從網站描述:
htmlcxx是用於C ++的簡單的非驗證css1和html解析器。
可以嘗試像tidyHTML庫- http://tidy.sourceforge.net (免費)
如果您使用的是Qt 4.6,則可以使用QWebElement。 一個簡單的例子:
frame-> setHtml(HTML); QWebElement document = frame-> documentElement(); QList imgs = document.findAll(“ img”); 這是另一個例子。 http://doc.qt.digia.com/4.6/webkit-simpleselector.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.