2016-06-08 18 views
0

我有以下HTML代碼。如何使用HTML標籤之間的文本訪問元素 - Selenium WebDriver

<span class="ng-binding" ng-bind="::result.display">All Sector ETFs</span> 

<span class="ng-binding" ng-bind="::result.display">China Macro Assets</span> 

<span class="ng-binding" ng-bind="::result.display">Consumer Discretionary (XLY)</span> 

<span class="ng-binding" ng-bind="::result.display">Consumer Staples (XLP)</span> 

可以看出,除了標籤之間的文本以外,標籤對於每一行都是相同的。 如何根據標籤之間的文本分別訪問上述各行。

+0

u能張貼父HTML源代碼中,這個跨度標籤撒謊 –

回答

2

使用下面的XPath的

//span[text()='All Sector ETFs'] 
1

您可以使用XPath功能文本()來。 例如

//span[text()="All Sector ETFs"] 

找到第一跨度

1

您可以使用下面的XPath基於文本

String text = 'Your text'; 
//text may be ==>All Sector ETFs, China Macro Assets, Consumer Discretionary (XLY), Consumer Staples (XLP) 
String xPath = "//*[contains(text(),'"+text+"')]"; 

通過這個,你可以找到每個元素找到所需的元素..

希望它會幫助你.. :)

+0

其實文可能是一切。你正在使用包含,只要它匹配一個元素文本的一部分,它會發現一些東西。 – RemcoW

0

嗨,請做它像貝洛w^

一號

public static void main(String[] args) { 
WebDriver driver = new FirefoxDriver(); 

List<WebElement> mySpanTags = driver.findElements(By.xpath("ur xpath")); 
System.out.println("Count the number of total tags : " + mySpanTags.size()); 
    // print the value of the tags one by one 
    // or do whatever you want to do with a specific tag 

for(int i=0;i<mySpanTags.size();i++){ 
System.out.println("Value in the tag is : " + mySpanTags.get(i).getText()); 
// either perform next operation inside this for loop 
if(mySpanTags.get(i).getText().equals("Consumer Staples (XLP)")){ 
    // perform your operation here 
    mySpanTags.get(i).click(); // clicks on the span tag 
     } 
    } 

    // or perform next operations on span tag here outside the for loop 
    // in this case use index for a specific tag (e.g below) 
    mySpanTags.get(3).click(); // clicks on the 4 th span tag 

} 

路兩

找到標籤直接//span[text()='Consumer Staples (XLP)']

相關問題