c++ - A 内的 Gumbo HTML 文本

标签 c++ qt gumbo

我正在使用 Gumbo 解析 CP1251 中的网页。我已将文本转换为 UTF-8 并将其发送到gumbo 解析器。我在使用

获取 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>

最佳答案

我终于总结出了一些例子。文本包含在子节点内。

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;
}

关于c++ - A 内的 Gumbo HTML 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25825019/

相关文章:

c++ - 类变量中类方法的列表/vector

c++ - std::map 中某个键的值可以被锁定吗?

c++ - QWidget::insertAction 尝试在运行时插入空操作

c++ - OpenCV:使用 imwrite() 函数时无法编译

c++ - 以编程方式获取环回接口(interface)/C++

c++ - Programm parallel QThread 在应用程序退出时创建内存泄漏

c++ - Qt 模糊 QMovie(来自 gif)

c++ - 在 C++ 类实现中调用 C 函数

apache-flex - Flex 4 中的自定义预加载器?