我正在尝试获取Internet Explorer web浏览器窗口的文本内容。
我遵循以下步骤:
- 获取指向IHTMLDocument2的指针
- 从IHTMLDocument2,我获得作为IHTMLElement的主体
3。在主体上,我调用get_innerText
编辑
- 我获取了主体的所有子元素,并尝试对所有IHTML元素进行递归调用
- 如果我得到任何不可见的元素,或者如果我得到一个标记为script的元素,我会忽略该元素及其所有子元素
我的问题是
- 除了页面上可见的文本,我还获得了style="display:none"的内容
- 对于google.com,我还获得了javascript和文本
我尝试过递归方法,但我不知道如何处理这样的场景,
<div>
Hello World 1
<div style="display: none">Hello world 2</div>
</div>
在这种情况下,我将无法获得"Hello World 1"
有人能帮我找到从IHTMLDocument2*获取文本的最佳方式吗。我使用的是C++Win32,没有MFC,ATL。
谢谢,Ashish。
如果在document.body.all
元素上向后迭代,则始终从内到外遍历元素。所以你不需要自己递归行走。DOM将为您做到这一点。例如(代码在Delphi中):
procedure Test();
var
document, el: OleVariant;
i: Integer;
begin
document := CreateComObject(CLASS_HTMLDocument) as IDispatch;
document.open;
document.write('<div>Hello World 1<div style="display: none">Hello world 2<div>This DIV is also invisible</div></div></div>');
document.close;
for i := document.body.all.length - 1 downto 0 do // iterate backwards
begin
el := document.body.all.item(i);
// filter the elements
if (el.style.display = 'none') then
begin
el.removeNode(true);
end;
end;
ShowMessage(document.body.innerText);
end;
附带评论:至于您使用递归方法的场景:
<div>Hello World 1<div style="display: none">Hello world 2</div></div>
例如,如果我们的元素是第一个DIV,则el.getAdjacentText('afterBegin')
将返回"Hello World 1"
。因此,我们可能可以在元素上向前迭代并收集getAdjacentText('afterBegin')
,但这有点困难,因为我们需要测试每个元素的父元素的el.currentStyle.display
。