2017-02-14 84 views
1

我被困在一端,我无法获得文本值。Selenium使用xpath - 如何使用他们的兄弟元素文本获取元素文本

为了更好的看法: -

<div class=""> 
<span class="address_city">Glenwood</span> 
<span class="address_state">GA</span> 
<span class="address_zip xh-highlight">30428</span> 
</div> 

我确定类address_zip...使用以下XPath:

//*[contains(text(),'30428')] 

我怎样才能得到文本值GA格伦伍德

回答

1

您可以使用preceding-sibling

//*[contains(text(),'30428')]/preceding-sibling::span[@class='address_city'] 
//*[contains(text(),'30428')]/preceding-sibling::span[@class='address_state'] 

您也可以找到邮政编码元素并使用它

WebElement zip = driver.findElement(By.xpath("//*[contains(text(),'30428')]")); 
String city = zip.findElement(By.xpath("//preceding-sibling::span[@class='address_city']")).getText(); 
String state = zip.findElement(By.xpath("//preceding-sibling::span[@class='address_state']")).getText(); 
+0

谢谢,那是我正在寻找。 – cod

0

你为什么不只是使用:

string city =Driver.FindElement(By.ClassName("address_city")).Text; 
string state =Driver.FindElement(By.ClassName("address_state")).Text; 

的情况下,这些类被复制其他元素:

//first get the zip as you are doing now. 
IWebElement zip=Driver.FindElement(By.Xpath("//*[contains(text(),'30428')]")); 

//now get the father element. 
IWebElement father=zip.FindElement(By.XPath("..")); 

//now get all the spans 
IList<IWebElement> allElements=father.FindElements(By.TagName("span")); 

//reach the elements you want. 
IWebElement city=allElements.ElementAt(0); 
IWebElement state=allElements.ElementAt(1); 
+1

它不会工作,因为有相同的重复的类名称,这就是为什么我问,有什么办法从文本()指向上面的两个元素。 – cod

0

它将无法工作,怎么有重复的类名相同的,这就是为什么我问的是有没有办法从文本(),以上面的两个元素指向。

您可以使用下面xpath: -

  • 为了得到格伦伍德文本:

    .//div[span[text() = '30428']]/span[@class = 'address_city'] 
    
  • 为了得到GA文本:

    .//div[span[text() = '30428']]/span[@class = 'address_state'] 
    
0

// [含有(文本(), '30428')] /前同辈::跨度[含有(@类, 'ADDRESS_CITY')] // [含有(文本(),” 30428 ')] /前同辈::跨度[含有(@类,' ADDRESS_STATE')]

0

尝试以下这些提到的xpath

获得值GA

//span[text()= '30428']/..//preceding-sibling::span[text()= 'GA')] 

xpath的说明: -使用text方法以及<span>标记,并使用preceding-sibling keyword继续使用另一个<span>标记。

OR

//span[text()= 'Glenwood']/following-sibling::span[text()= 'GA'] 

的XPath的说明: -使用text<span>标签以及方法和使用following-sibling keyword另一<span>标签前进。

OR

//span[text()= 'Glenwood']/..//following-sibling::span[text()= 'GA'] 

的XPath的说明: -使用text<span>标签以及方法和使用following-sibling keyword另一<span>标签前进。

获得价值格伦伍德

的XPath
//span[text()= 'GA']/..//preceding-sibling::span[text()= 'Glenwood'] 

说明: -使用text<span>标签以及方法和使用preceding-sibling keyword另一<span>标签前进。

相关问题