使用 xpath 的 Selenium - 如何使用其兄弟元素文本获取元素文本

Selenium using xpath - How to get elements text using their sibling element text

我卡在一端,无法获取文本值。

为了更好的观看:-

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

我使用以下 xpath 识别 class address_zip... :

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

如何获取文本值 GAGlenwood

你为什么不直接使用:

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);

您可以使用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();

It won't work , coz there is duplicate class name for same , Thats why I ask that is there any way to point from text() to upper two element.

您可以使用下面的 xpath :-

  • 要获取 Glenwood 文本:

    .//div[span[text() = '30428']]/span[@class = 'address_city']
    
  • 获取GA文本:

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

//[包含(text(),'30428')]/preceding-sibling::span[包含(@class,'address_city')] //[包含(text(),'30428')]/preceding-sibling::span[包含(@class,'address_state')]

试试下面提到的这些 xpath

获取 GA

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

xpath 的解释:-text 方法与 <span> 标记一起使用,然后使用 [=18 继续使用另一个 <span> 标记=].

OR

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

xpath 的解释:- 使用 text 方法和 <span> 标签,然后使用 [=22 使用另一个 <span> 标签=].

OR

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

xpath 的解释:- 使用 text 方法和 <span> 标签,然后使用 [=22 使用另一个 <span> 标签=].

获取 Glenwood

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

xpath 的解释:-text 方法与 <span> 标记一起使用,然后使用 [=18 继续使用另一个 <span> 标记=].