5,927
社区成员




procedure TForm1.WebBrowser1DocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
var
doc: IHTMLDocument2;
em: IHtmlElement;
colLink: IHTMLDocument2;
begin
if WebBrowser1.Application=pDisp then begin
showmessage('Web download is over.');
doc := WebBrowser1.Document as IHTMLDocument2;
if doc <> nil then begin
em := GetHtmlElement(doc, 'links','innerText','新浪科技');
//em.setAttribute('target', '_self', 0);//无效果
if em<>nil then
em.click; //点击
end
else begin
showmessage('Html doc is null.');
end;
end;
end;
{
自定义函数,获取满足条件的标签
tagName:标签名 关键字:all,links,images,applets,forms,anchors,scripts,embeds,plugins,parentWindow
atName: 属性名 关键字:innerText(暂时只处理这个),
atValue:属性值
}
function TForm1.GetHtmlElement(doc:IHTMLDocument2; tagName,atName,atValue:string):IHtmlElement;
var
col: IHTMLElementCollection;
em: IHtmlElement;
i: Integer;
begin
if doc <> nil then begin
//判断标签名
if tagName = '' then
col := doc.all As IHTMLElementCollection
else if tagName = 'all' then
col := doc.all As IHTMLElementCollection
else if tagName = 'links' then
col := doc.links As IHTMLElementCollection
else if tagName = 'images' then
col := doc.images As IHTMLElementCollection
else if tagName = 'applets' then
col := doc.applets As IHTMLElementCollection
else if tagName = 'forms' then
col := doc.forms As IHTMLElementCollection
else if tagName = 'anchors' then
col := doc.anchors As IHTMLElementCollection
else if tagName = 'scripts' then
col := doc.scripts As IHTMLElementCollection
else if tagName = 'embeds' then
col := doc.embeds As IHTMLElementCollection
else if tagName = 'plugins' then
col := doc.plugins As IHTMLElementCollection
else if tagName = 'parentWindow' then
col := doc.parentWindow As IHTMLElementCollection
else
col := doc.all.tags(tagName) As IHTMLElementCollection;
//判断标签的id及name,如果都没有则返回,查询条件不足;
if (atName='') or (atValue='') then begin
showmessage('GetHtmlElement error:查询条件不足');
exit;
end;
//循环标签容器,开始获取满足条件的第一个元素
for i := 0 to col.length - 1 do begin
em := col.item(i,0) as IHtmlElement;
if atName='innerText' then begin
if atValue=em.innerText then begin
result := em;
end;
end
else if atValue=em.getAttribute(atName,0) then begin
result := em;
exit;
end;
end;
end else begin
showmessage('GetHtmlElement error:Html doc is null.');
exit;
end;
end;