2014-09-13 15 views
1

我使用Gumbo解析CP1251中的网页。我已将文本转换为UTF-8并将它发送给了gumbo解析器。我有问题,获取文本里面A链路与A区内的HTML文本A

node->v.text.text 

我得到的输出奇怪的符号,而源在控制台中正确显示。 我使用Qt 5.2libiconv进行转换。

需要我将节点文本转换为本地代码页或我做错了什么?

获取页面CP1251

QByteArray barrData = pf->getData(); 

    size_t dstlen = 1048576; 
    char buf[dstlen]; 
    memset((char*)buf, 0, dstlen); 

    char* pIn = barrData.data(); 
    char* pOut = (char*)buf; 

    size_t srclen = barrData.size(); 


    iconv_t conv = iconv_open("UTF-8", "CP1251"); 
    iconv(conv, &pIn, &srclen, &pOut, &dstlen); 
    iconv_close(conv); 

    GumboOutput* output = gumbo_parse(buf); 

    parsePage(output->root); 
    gumbo_destroy_output(&kGumboDefaultOptions, output); 

解析

if (node->v.element.tag == GUMBO_TAG_DIV && (_class = gumbo_get_attribute(&node->v.element.attributes, "class"))) 
{ 
    if (QString(_class->value) == "catalog-item-title") 
    { 
     qDebug() << "parsePage: found product, parsing..."; 

     GumboVector* children = &node->v.element.children; 
     for (int i = 0; i < children->length; ++i) 
     { 
      GumboNode* node = static_cast<GumboNode*>(children->data[i]); 

      GumboAttribute* href; 
      GumboAttribute* id; 

      if (node->v.element.tag == GUMBO_TAG_A && 
       (href = gumbo_get_attribute(&node->v.element.attributes, "href")) 
      ) 
      { 
       char buf[1024]; 
       memset(buf, 0, 1024); 
       int i = node->v.text.original_text.length; 
       memcpy(buf, node->v.text.original_text.data, i); 


       QString strTitle = buf; 
       Q_ASSERT(node->v.text.original_text.length > 0); 
       qDebug() << "parsePage: found product" << strTitle << href->value; 

       break; 
      } 
     } 
    } 
} 

来源页面文字:

<div class="catalog-item-title"><a href="/textile/postelnoe-bele/korolevskoe-iskushenie-perkal/izmir_2/">Измир 2</a></div> 

回答

1

我终于抽了例子。文本包含在子节点内。

  if (node->v.element.tag == GUMBO_TAG_A && 
       (href = gumbo_get_attribute(&node->v.element.attributes, "href")) 
      ) 
      { 
       QString strTitle; 
       GumboNode* title_text = static_cast<GumboNode>*)(node->v.element.children.data[0]); 
       if (title_text->type == GUMBO_NODE_TEXT) 
       { 
        strTitle = title_text->v.text.text; 
       } 

       qDebug() << "parsePage: found product" << strTitle << href->value; 

       break; 
      } 
+1

出于好奇,你从哪里找到Gumbo的文档? GitHub页面没有链接到它,我通过Google http://matze.github.io/clib-doc/gumbo-parser/index.html找到的这个链接也没有太大的帮助:例如,什么是GumboOutput结构看起来像,我该如何使用它? – Michael 2015-04-22 17:37:34

+0

你的代码很有用,我不得不投票! – 2016-06-21 23:28:39

相关问题