【问题标题】:Issue selecting an xpath when it is unknown if it will be on the page当未知 xpath 是否会在页面上时,选择 xpath 的问题
【发布时间】:2016-02-02 05:39:02
【问题描述】:

我正在尝试编写这段 selenium 代码,它将在页面底部选择一个页码指示器并计算其上的元素。但是,如果只有一页,则不会出现此数字指示符,并且将来会更新并最终包含多页。

如果发现页码指示符存在,我怎样才能让一段 selenium 代码选择最后一页?我让它在网页上搜索一段仅在出现指示符时才会出现的文本,但我一直坚持在那之后要做什么才能选择页码指示器中的最后一页。

<div class="view view-blog view-id-blog view-display-id-page_1 view-dom-id-3e6e5f93bb52f8bc5f35e55c6da86526">
<div class="view-filters">
<form id="views-exposed-form-blog-page-1" class="views-exposed-form-blog-page-1" accept-charset="UTF-8" method="get" action="/blogs">
</div>
<div class="view-content">
<div class="item-list">
</div>
<h2 class="element-invisible">Pages</h2>
<ul class="pager">
<li class="pager__item pager__item--current">1</li>
<li class="pager__item">
<li class="pager__item">
<li class="pager__item">
<li class="pager__item">    
<li class="pager__item">
<li class="pager__item pager__item--next">
<li class="pager__item pager__item--last">

&lt;li class="pager__item pager__item--last"&gt; 是对应我要选择的按钮的文本。

这里有 5 页,所以它会转到第 5 页,但我正在尝试编写它以便它只转到当前列表中的最后一页,这样我就不必硬编码一个数字来跳转到。

我当前的代码只是

if (driver.getPageSource().contains("pager")) {
            WebElement k = driver.getPageSource().findElement("pager__item pager__item--last");

pager__item pager__item--last 是代码内的字符串,对应于我要选择的按钮&lt;li class="pager__item pager__item--last"&gt;

如果您不确定它是否存在于您的代码中,那么搜索此字符串然后单击它对应的按钮是什么好方法?

谢谢

【问题讨论】:

    标签: java html selenium xpath


    【解决方案1】:

    以谷歌搜索结果为例

    1. 为页码指示符编写条件语句
    2. 当条件满足时,使用 FindElements 方法获取所有代表页码的&lt;a&gt;标签
    3. 从列表中获取最后一页的 Last 元素
    4. 点击元素

    【讨论】:

      【解决方案2】:

      最好的方法是使用 try catch..

      try{
      driver.findElementByXpath("Your xpath of last page button").click();//you can use any other locator
      }catch(NoSuchElementException e){
      //if you get exception then it means that element is not present(it means there is only one page)
      //if you have multiple page then that button will be present and it'll not through any exception and it will trigger click event in that element and you'll get navigated to last page
      }
      

      【讨论】:

        猜你喜欢
        • 2016-03-12
        • 1970-01-01
        • 2012-08-12
        • 2021-12-10
        • 2023-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多