//strHtml : html源代码;
//TagName : 节点名称
//AttrName : 节点属性名称
//AttrValue : 节点属性值
//outItems : 匹配节点输出, 每行一个匹配节点
procedure xQuery(strHtml, TagName, AttrName, AttrValue: string; outItems: TStringList);比如html代码如下, 现在要取得TagName=div, AttrName=id, AttrValue=content1节点(就是<div id="content1">...</div>)的源代码, 该如何实现?另外如果参数AttrName或者AttrValue为空, 则表示匹配所有!谢谢!<body>
<div id="content1">
<div>
</div>
<div>
</div>
<div>
</div>
</div>
<div id="content2">
<div>
</div>
<div>
</div>
<div>
</div>
</div></body>
//TagName : 节点名称
//AttrName : 节点属性名称
//AttrValue : 节点属性值
//outItems : 匹配节点输出, 每行一个匹配节点
procedure xQuery(strHtml, TagName, AttrName, AttrValue: string; outItems: TStringList);比如html代码如下, 现在要取得TagName=div, AttrName=id, AttrValue=content1节点(就是<div id="content1">...</div>)的源代码, 该如何实现?另外如果参数AttrName或者AttrValue为空, 则表示匹配所有!谢谢!<body>
<div id="content1">
<div>
</div>
<div>
</div>
<div>
</div>
</div>
<div id="content2">
<div>
</div>
<div>
</div>
<div>
</div>
</div></body>
那我的回复也复制下:html的代码如果不标准,IE上也能显示. 比如:可能有的标签有前面的部分: <...>,却没有后面的 </...> 如果是比较规范的html代码,你看能不能用XML来解析它.如果可以的话,就直接可以find里面的node了. 但是,还有个问题,对于成对出现的标签, <tagname attribname="">...... </tagname>这样的还好.
有些标签,比如 <image src="a.gif"> 它后面不是以"/>"结尾的,即这样的形式: <image src="a.gif"/>,
不知道xml是否支持,没试过.
if TagRet <= 0 then Exit;
R := PosEx(AttName, Source, TagRet);
if R <= 0 then Exit;
AttValue = Source + 起始R + Length(AttName) + 忽略['=', '"', '''']
,长度就是从起始检测到[' ', '"', '''']if AttValue <> 目标AttValue then return;找到,则从TagRet到最后结尾这个语法分析一下就好,很简单的。
以下为代码,未测试,不保证能运行,但是思路正确。
自己做容错吧:
procedure GetElements(TagName, AttrName, AttrValue: string;outItems:TStringList);
var
doc: IHTMLDocument2;
Elements: IHTMLElementCollection;
i, EleCount: Integer;
begin
doc := webbrowser1.document as IHTMLdocument2;
Elements := doc.all.tags(TagName) as IHTMLElementCollection; //获取 tagname相同的全部元素集合
if AttrValue <> '' then // AttrValue不为空时
begin
if AttrName = 'id' then // AttrName为id时全局唯一。
begin
outItems.Text := (Elements.item(AttrValue, 0) as IHTMLelement).outerHTML;
Exit;
end
else if AttrName = 'name' then // AttrName为name时可能不唯一。
begin
Elements := Elements.item(AttrValue, 0) as IHTMLelementcollection;
EleCount := Elements.length;
for i := 0 to EleCount - 1 do
begin
outItems.Add((Elements.item(i, 2) as IHTMLelement).outerHTML)
end;
Exit;
end
else // AttrName既不是id也不是name时,则为其他属性
begin
Elements := Elements.item(AttrValue, 0) as IHTMLelementcollection;
EleCount := Elements.length;
for i := 0 to EleCount - 1 do
begin
if (Elements.item(i, 2) as IHTMLelement).getAttribute(AttrName, 0) = AttrValue then
outItems.Add((Elements.item(i, 2) as IHTMLelement).outerHTML)
end;
Exit;
end;
end
else // AttrValue为空时 获取全部元素
begin
EleCount := Elements.length;
for i := 0 to EleCount - 1 do
begin
outItems.Add((Elements.item(i, 2) as IHTMLelement).outerHTML)
end;
Exit;
end;end;