【问题标题】:getElementsByTagName with IHTMLDocument3 randomly returns nothing带有 IHTMLDocument3 的 getElementsByTagName 随机返回任何内容
【发布时间】:2017-08-08 16:06:00
【问题描述】:

我正在尝试从一个 c++ 程序填充 Internet Explorer 中的一些表单输入字段,但我遇到了一个随机错误,我希望这是因为我的代码:

UINT msg = RegisterWindowMessage("WM_HTML_GETOBJECT");
LRESULT result = 0;
SendMessageTimeout(hwnd, msg, NULL, NULL, SMTO_ABORTIFHUNG, 10000, (PDWORD_PTR)&result);
if (!result)
    return;


// get main document object
IHTMLDocument3 *doc = NULL;
ObjectFromLresult(result, IID_IHTMLDocument3, NULL, (void**)&doc);
if (!doc)
    return;

VARIANT varint, varstr;
varint.vt = VT_I4;
varstr.vt = VT_BSTR;


IHTMLElementCollection* pElemCollections=NULL;


if (FAILED(doc->getElementsByTagName(L"input", &pElemCollections)))
    return;

long nelm;
pElemCollections->get_length(&nelm);

...

在最后一行和同一页面上使用相同的 HWND 时,有时我会得到正确的数字或​​输入字段,而 nelm 经常得到 0。

您是否发现我的代码有问题或者是错误? 请注意,我验证了 HWND 是正确的,并且永远不会调用 return

谢谢

【问题讨论】:

  • 发生这种情况时 IHTMLDocument2::get_readyState 的结果是什么?
  • get_readyState 返回“完成”,我可以毫无问题地获得 IHTMLDocument2::get_body。有时,如果我得到 nelm=0 并返回调试器以将输入更改为 INPUT 并再次运行该行,它可以工作,但它也是随机的。
  • 使用该代码我可以让它工作(对于 A 标签):BSTR tag = L"A"; long nelm; int n = 0; do { n++; if (tag == L"a") tag = L"A"; else tag = L"a"; if (pElemCollections) pElemCollections->Release(); if(FAILED(doc>getElementsByTagName(tag,&pElemCollections))) return; pElemCollections->get_length(&nelm); } while (nelm == 0);
  • 我修改了这段代码,因为使用 BSTR 非常糟糕。此外,通过初始化 BSTR(最终为 CComBSTR)并将其用作 getElementsByTagName 的参数,我似乎有更少的错误(或没有错误)......

标签: c++ ihtmldocument2 ihtmldocument


【解决方案1】:

这样做我没有问题了:

UINT msg = RegisterWindowMessage("WM_HTML_GETOBJECT");
LRESULT result = 0;
SendMessageTimeout(hwnd, msg, NULL, NULL, SMTO_ABORTIFHUNG, 10000, (PDWORD_PTR)&result);
if (!result)
    return;


// get main document object
IHTMLDocument3 *doc = NULL;
ObjectFromLresult(result, IID_IHTMLDocument3, NULL, (void**)&doc);
if (!doc)
    return;

CComVariant varint;
CComVariant varstr;


IHTMLElementCollection* pElemCollections=NULL;

CComBSTR name(L"input")
if (FAILED(doc->getElementsByTagName(name, &pElemCollections)))
    return;

long nelm;
pElemCollections->get_length(&nelm);

...

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 2018-02-22
    • 2020-04-22
    • 2018-07-30
    • 2012-08-23
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多