HTML Dom是一个访问HTML文档的W3C标准。它定义了如何去访问页面元素对象以及属性和方法。
在DOM标准里面:
1 整个HTML文档是一个文档节点。
2 每一个HTML 标签都是一个元素节点。
3 HTML 文本都是文本节点。
4 每一个HTML 属性都是一个属性节点。
HTML DOM 的一些主要属性(x是一个HTEML元素)
x.innerHtml - the inner text value of x (a HTML element)
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x
HTML DOM 的一些主要方法(x是一个HTEML元素)
x.getElementById(id) - get the element with a specified id
x.getElementsByTagName(name) - get all elements with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x
通常访问HTML DOM节点有一下三种方法:
1 使用getElementById()
node.getElementsByTagName("tagname");
2 使用getElementsByTagName()
x=document.getElementsByTagName("p");
For i = 0 to x.Length - 1
Print x(i).innerText
3 使用HTML文档的节点树导航
node.firstChild
node.childNodes
node.parentNode
掌握HTML DOM对qtp web测试是很有帮助的。
下面有个简单的例子,在开心网上搜索好友列表并把相应的车位状态取出来。如果用qtp实现的话有下面几个难点,好友的列表的长度是动态变化的,好友名称是不固定的,不同的登陆用户有不同的好友。
使用HTML DOM就可以比较方便的解决找个问题,查看页面源代码我们知道每一个好友都是存在一个"UL"标签里面,而好友的车位状态是存在"LI"标签的子节点里面。
Function Find_Park()
Dim d
Set d = createobject("scrīpting.dictionary")
'Get all the "UL" tag from the page, each object contains the information of one friend
Set friends = Browser("争车位 - 开心网").Page("争车位 - 开心网").Object.getElementsByTagName("ul")
For i = 0 to friends.Length - 1
'Get all the "LI" tag within each friend, one object whose style is "FLOAT: right" contain the status of the park
Set friendAttrs = friends(i).GetElementsByTagName("li")
blnFlag = False
For j = 0 to friendAttrs.Length - 1
If strComp("FLOAT: right", friendAttrs(j).style.csstext, 1) = 0 Then
Set imgs = friendAttrs(j).GetElementsByTagName("img")
d.Add friends(i).InnerText, imgs(0).GetAttribute("alt")
blnFlag = True
Exit For
End If
Next
If Not blnFlag Then
d.Add friends(i).InnerText, "空"
End If
Next
Set Find_Park = d
End Function