【问题标题】:Not able to get the locate the element by using xpath or css selector无法通过使用 xpath 或 css 选择器来定位元素
【发布时间】:2021-11-15 02:21:37
【问题描述】:
<div class="et_pb_button_module_wrapper et_pb_button_4_tb_header_wrapper et_pb_button_alignment_center et_pb_button_alignment_phone_center et_pb_module "> 
   <a class="et_pb_button et_pb_button_4_tb_header full-width-btn et_hover_enabled et_pb_bg_layout_light" href="https://pegramonline.com/compare-insurance-companies-charlotte-nc/">Get a Quote</a>
</div>

我试图找到 &lt;a&gt; 元素,但仍然找不到它。请有其他建议...类名有空格

By.cssSelector(“a[class='et_pb_button et_pb_button_4_tb_header full-width-btn et_hover_enabled et_pb_bg_layout_light']”);

By.cssSelector(“a.et_pb_button.et_pb_button_4_tb_header.full-width-btn.et_hover_enabled.et_pb_bg_layout_light”);

By.xpath(“//a[contains(@class, 'et_pb_button') and contains(@class, 'et_pb_button_4_tb_header') and contains(@class, 'full-width-btn') 并且包含(@class, 'et_hover_enabled') 和包含(@class, 'et_pb_bg_layout_light')]”);

【问题讨论】:

    标签: selenium-webdriver css-selectors


    【解决方案1】:

    如果您尝试在此 CODE

    中放置属性颜色或其他任何内容,它会正常工作
    a.et_pb_button.et_pb_button_4_tb_header.full-width-btn.et_hover_enabled.et_pb_bg_layout_light{
        color:red;
    }
    

    或者

    a[class=’et_pb_button et_pb_button_4_tb_header full-width-btn et_hover_enabled et_pb_bg_layout_light’]{
        color:red;
    }
    

    那么你可以很容易地理解它工作正常。

    【讨论】:

      【解决方案2】:

      在 Selenium 中有 4 种点击方式。

      使用下面的 xpath

      //a[contains(text(),'Get a Quote')]
      

      代码试用 1:

      Thread.sleep(5);
      driver.findElement(By.xpath("//a[contains(text(),'Get a Quote')]")).click();
      

      代码试用 2:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(),'Get a Quote')]"))).click();
      

      代码试用 3:

      Thread.sleep(5);
      WebElement button = driver.findElement(By.xpath("//a[contains(text(),'Get a Quote')]"));
      ((JavascriptExecutor)driver).executeScript("arguments[0].click();", button);
      

      代码试用 4:

      Thread.sleep(5);
      WebElement button  = driver.findElement(By.xpath("//a[contains(text(),'Get a Quote')]"));
      new Actions(driver).moveToElement(button).click().build().perform();
      

      PS:如果我们在HTML DOM 中有唯一条目,请检查dev tools(谷歌浏览器)。

      检查步骤:

      Press F12 in Chrome -> 转到element 部分 -> 做一个CTRL + F -> 然后粘贴xpath 看看,如果你想要的element 用@ 得到突出显示 987654333@匹配节点。

      【讨论】:

      • 我验证了它只有 1 个元素。为什么我不想使用 driver.findElement(By.xpath("//a[contains(text(),'Get a Quote')]")) 是我在同一页面上有多个链接具有相同的文本和我想单独测试所有链接。
      猜你喜欢
      • 2019-12-25
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2020-03-05
      • 2019-07-20
      相关资源
      最近更新 更多