I have an HTML page containing the following code :
<table class="report" style="width:100%">
<tbody>
<tr>
<th/>
<th>Position Open
<br>
<span class="timestamp">27/7/2016 16:12:12</span>
</br>
</th>
<th>Position closed
<br>
<span class="timestamp">27/7/2016 16:12:42</span>
</br>
</th>
</tr>
<tr>
<td>
<span dir="ltr">EURJPY</span>
</td>
<td>116.098</td>
<td>116.156</td>
</tr>
</tbody>
</table>
On this page I have another table with the same class attribute "report" but only this table contains texts "Position Open" and "Position Closed". I need to select elements containing the "EURJPY", "116.098" and "116.156" data. These elements content is changing ie instead of "EURJPY" may appear "EURUSD" or "GBPCAD" etc. I tried the following code:
driver.findElement(By.xpath("//span[text()='Position Open']/ancestor::table[@class='report'](//tr)[2]/td/span")).getAttribute("textContent");
to get the first required field text but got the Invalid selector
error.
Your XPath is close but there were a couple issues.
//span[text()='Position Open']/ancestor::table[@class='report'](//tr)[2]/td/span
You are searching for a SPAN
that contains the text 'Position Open' when in fact it is a TH
that contains the text.
//th[text()='Position Open']/ancestor::table[@class='report'](//tr)[2]/td/span
(//tr)
should be corrected to //tr
//th[text()='Position Open']/ancestor::table[@class='report']//tr[2]/td/span
What you want is the text contained in the TD
, not the SPAN
. If you pull the text from the TD
you can get the text you want from all three elements. If you pull the SPAN
, then you will also need to pull the last two TD
s. This way is just simpler.
...and finally, the TH
contains more than just the text you are looking for. Use .contains()
to get a match.
//th[text()='Position Open']/ancestor::table[@class='report']//tr[2]/td
So we take that XPath and put it into Java code and we get the below.
List<WebElement> tds = driver.findElements(By.xpath("//th[contains(text(),'Position Open')]/ancestor::table[@class='report']//tr[2]/td"));
for (WebElement td : tds)
{
System.out.println(td.getText());
}
有时会出现与文本匹配的问题,请改用use contains,尝试使用此选择器
//th[contains(.,'Position')]/ancestor::table[@class='report']//tr[2]/td/span
You can use this xpath
to locate the 3 <td>
tags you are interest in
//th[contains(text(),'Position Open')]/ancestor::table//tr[2]/td
Using it will give you list of three elements, you can extract the text from them
List<WebElement> tds = driver.findElement(By.xpath"//th[contains(text(),'Position Open')]/ancestor::table//tr[2]/td");
String currency = tds.get(1).getText(); // this will be EURJPY
tds.get(2).getText(); // 116.098
tds.get(3).getText(); // 116.156
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.