从IHTMLDocument2*获取页面上的可见文本
Obtaining visible text on a page from an IHTMLDocument2*
我正在尝试获取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
。
相关文章:
- 文本文件中的单词链表
- 从命令行c++发送文本文件名
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 如何创建一个QTableWidgetItem,用长文本右对齐,左边有省略号
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何根据单词在文本中出现的概率输出单词
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端