简体   繁体   English

如何使用 Selenium 和 JavaScript 检查 class 中是否存在文本

[英]How to check if text exist inside class using Selenium and JavaScript

I'm new to Selenium.我是 Selenium 的新手。 I like to verify if a specific class contains a text snippet in JavaScript.我想验证特定的 class 是否包含 JavaScript 中的文本片段。

I have following HTML:我有以下 HTML:

<div class="product-small">
   <div class="data">
      <p>This is some Text</p>
   </div>
</div>
<div class="product-small">
   <div class="data">
      <p>This is some Text</p>
   </div>
</div>
...

The above class are available multiple times on the page, so i have to iterate the "product-small" class to check if all 12 classes contains the text "some".上面的 class 在页面上多次可用,所以我必须迭代“product-small” class 以检查是否所有 12 个类都包含文本“some”。 If one of the 12 elements with that "product-small" class does not contain the text "some", the test will fail.如果具有“product-small” class 的 12 个元素之一不包含文本“some”,则测试将失败。

I thought something like this:我想是这样的:

const cars = driver.findElements(By.className('product-small'));
    cars.forEach(function (element) {
        // Check if element contains "some" inside class "data"
        // If element does not contain "some", test will fail
    });

Thank you:)谢谢:)

A generic solution would be to collect the elements using the following based Locator Strategy and probe the length, if it equals to 12 then mark it as Pass else mark it as Fail一个通用的解决方案是使用以下基于定位器策略收集元素并探测长度,如果它等于12 ,则将其标记为通过,否则将其标记为失败

const cars = driver.findElements(By.xpath("div[@class='product-small']//p[contains(., 'some')]"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM