java - 获取页面中多次出现的div的xpath

标签 java css selenium xpath selenium-webdriver

我有一个奇怪的要求。我有一个名为“expandThisSection”的 div 类。而我有

<div id=​"requiredAccessoriesContentPlaceHolder" class=​"expandThisSection">​No required accessories are available for this product.​</div>​

<div id=​"requiredAccessoriesContentPlaceHolderMeasurement" class=​"expandThisSection">​&nbsp;​</div>​

<div id=​"optionalAccessoriesContentPlaceHolder" class=​"expandThisSection">​No optional accessories are available for this product.​</div>​

<div id=​"optionalAccessoriesContentPlaceHolderMeasurement" class=​"expandThisSection">​&nbsp;​</div>​

 <div class=​"expandThisSection">​
    <div style=​"width:​95%">​mytext</div>​
    ​<ul class=​"movePos">​…​</ul>​
    <div><b>test</b>​</div>
    ​<div>​<b>abc</b> Get this text</div>
    ​<div id=​"vendLogo">​…​</div>
 </div>

<div class="expandThisSection">
    <table>...</table>
</div>

我想要具有 95% 宽度样式的 div 的内容。我想要的值是“mytext”。但是我无法找到相同的 xpath。

此外,我还需要 xpath 来查找位于 id= “vendLogo”的 div 上方的 div 内容。那就是我想要“获取此文本”。

注意:我保证这个粗体标签将包含“abc”

怎么做?我在 Java 中使用 Selenium

得到第一个。无法获得第二个。

代码:

List<WebElement> currentSkuDescription = driver.findElements(By.xpath("//div[@class='expandThisSection']/div"));
          for(WebElement currentItem: currentSkuDescription) {
              WebElement descriptionBlock = currentItem.findElement(By.xpath("//div[contains(@style, 'width:95%')]"));
              description= descriptionBlock.getText();
          }

最佳答案

尝试删除 @class='expandThisSection' 因为你想要的 div 没有那个类属性(它的父级有)。此外,完全匹配也是可能的。

By.xpath("//div[@style='width:95%']
By.xpath("//div[contains(@style, 'width:95%')]

这些都应该有效。如果您想确保相对于父对象抓取正确的对象,请使用 XPath 轴...

//div[contains(@class, 'expandThisSection')]/child::div[contains(@style, 'width:95%')]

关于java - 获取页面中多次出现的div的xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33675621/

相关文章:

java - java中使用子字符串和索引的范围错误

javascript - 滚动条应该在没有 setInterval() 的底部

html - 仅包含 html/css 的多个可折叠列表

css - 如何使用 flexbox 来创建砌体布局?

java - Selenium WebDriver 上传文件/关闭资源管理器窗口

python - 使用 selenium webdriver 登录网站时出错

java - java中一维数据的轻量级增量分类

java - 如何在eclipse插件中使用ElementTreeSelectionDialog

java - 在 Java 中测试 try-catch block

selenium - 通过 Xpath 获取元素 (Geb)