首先,html table是由 table 元素以及一個或多個 tr、th 或 td 元素組成。
for example:
這是一個簡單的html table:
源碼如下:
<html>
<head>
<meta http-equiv="content-language" content="zh-cn">
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</script>
</head>
<body>
<div align="center">
<h4 align="left"> table head:</h4>
<table border="2" width="90%" id="table138" bordercolorlight="#cccccc" cellspacing="0" cellpadding="0" bordercolordark="#cccccc" style="border-collapse: collapse">
<tr align="center">
<td height="26" width="10%" align="center" bgcolor="#cceeaa" ><strong>test case id</strong></td>
<td height="26" width="35%" align="center" bgcolor="#eeeeaa" ><strong>steps</strong></td>
<td height="26" width="30%" align="center" bgcolor="#00eeee" ><strong>expect</strong></td>
<td height="26" align="center" bgcolor="#ee00ee" ><strong>actual</strong></td>
<td height="26" align="center" bgcolor="#00ee00" ><strong>pass/fail</strong></td>
</tr>
<td height="26" align="center" bgcolor="#cceeaa">ent#-12345</td>
<td height="26" align="left" bgcolor="#eeeeaa" >1.open baidu.com ,wait for the page load</br>2.enter "selenium" in the input box" </br>3.click search button </td>
<td height="26" align="left" bgcolor="#ee00ee" >selenium - web browser automation is appear the page,but is not the first link</td>
<td height="26" align="center" bgcolor="#00ee00" >fail</td>
<td height="26" align="center" bgcolor="#cceeaa">ent#-12346</td>
<td height="26" align="left" bgcolor="#eeeeaa" >1.click the "selenium - web browser automation" link</br>2.wait for page load</td>
<td height="26" align="left" bgcolor="#00eeee" >open the official home page of selenium</td>
<td height="26" align="left" bgcolor="#ee00ee" >selenium home page is load </td>
<td height="26" align="center" bgcolor="#cceeaa">ent#-12347</td>
<td height="26" align="left" bgcolor="#eeeeaa" >1.click baidu snapshot of selenium web page </br>2. wait for the page load</td>
<td height="26" align="left" bgcolor="#00eeee" >the snapshot web page can be show up</td>
<td height="26" align="left" bgcolor="#ee00ee" >the snapshot web page is show up</td>
<td height="26" align="center" bgcolor="#00ee00" >pass</td>
</table>
</div>
</body>
</html>
那麼問題就來了,我想通過xpath擷取這個table的每一個cell的值(比如擷取expect的值),該怎麼做。
如果這個表格被改變了,增加或删除一些行列該如何處理?
我的solution是擷取table的base xpath,這個所謂的base xpath是指這個table的第n行第m列相同的部分,然後通過傳入n,m擷取傳回值
public static string tablecell(webdriver driver,int row, int column)
{
string text = null;
//avoid get the head line of the table
row=row+1;
string xpath="//*[@id='table138']/tbody/tr["+row+"]/td["+column+"]";
webelement table=driver.findelement(by.xpath(xpath)); //*[@id="table138"]/tbody/tr[1]/td[1]/strong
text=table.gettext();
return text;
}
是以,tablecell(driver,1,2)就能傳回
最新内容請見作者的github頁:http://qaseven.github.io/