【问题标题】:How to extract the dynamic text 3204255 from the html provided through Selenium?如何从 Selenium 提供的 html 中提取动态文本 3204255?
【发布时间】:2019-02-04 10:42:22
【问题描述】:

我正在尝试从 div 中获取数字。当我执行测试用例时,新数字正在显示,现在我想获取该数字,或者换句话说,在控制台中打印它。

我正在使用:

webElement webelement=driver.findElement(By.xpath("//div[contains(@class,'responsive now') and text()='Application number']"));
webelement.getText();

driver.findElement(By.xpath("//div[@class='responsive-show']")).getAttribute("value");

它不是关于定位器的compailining,但它没有显示数字。

<td> 
  <div class="responsive-show">Application number</div>
  "3204255" 
  <input data val="true" data-val-number="The field ExaminationNumber must be a number." data-val-required="The ExaminationNumber field is required." id="ActiveExamModeIs_0__ExaminationNumber" name="ActiveExamMode[0].ExaminationNumber" type="hidden" value="3204255"> 
  <input data -val="true" data-val-number="The field ExaminationEligibilityExamTypeId must be a number" data-val-required="The ExaminationEligibilityExamTypeId fiels is required." type="hidden" value="1">
</td>

【问题讨论】:

  • 为了帮助您更好地不要发布代码图像,请将您的html代码以文本格式发布。
  • 您的第一次尝试可能会奏效,但您使用的是“立即响应”而不是“响应显示”
  • 我还是修好了,没有收到文字
  • 申请号
    ==$0 "3204255"
  • 请将 HTML 发布为文本而不是图像,以便阅读。

标签: javascript java selenium selenium-webdriver


【解决方案1】:

总而言之:除非您想使用 "JavascriptExecutor"

另一种选择是使用简单的 selenium 操作从 &lt;td&gt; 元素中获取整个文本,然后使用字符串函数 substring() 来获取卡在引号 " 之间的应用程序编号值。

代码:

    String input = driver.findElement(By.xpath("//table[@class='table table-hover']/tbody/tr/td")).getAttribute("innerText");
    input = input.substring(input.indexOf("\"")+1, input.lastIndexOf("\""));
    System.out.println("Extracted Value" + input);

【讨论】:

    【解决方案2】:

    文本:3204247 不包含在 div 标签中,但它包含在 &lt;td&gt; 中。 你可以试试这个:

    webElement webelement=driver.findElement(By.xpath("//table[@class='table table-hover']/tbody/tr/td"));// you can improve this locator and can also use one below
    //webElement webelement=driver.findElement(By.xpath("//div[@class='responsive-show']/..")); using xpath axes
    String value=webelement.getText();// OR
    //String value=webelement.getAttribute("innerText");
    

    【讨论】:

    • 对我不起作用,我尝试添加一些等待时间,但也没有用
    • 有没有可能被隐藏了?
    • 您要查找的文本不在 div 标签中。我已经更新了我的答案。
    • 我没有 tr/td 文本 ==$0
      申请号
      "3204255"
    • 我在定位 tr/td 时遇到问题。请您帮帮我。
    【解决方案3】:

    根据您共享的 HTML 来提取数字,即 3204255 您需要诱导 WebDriverWait 以获得所需的 元素可见 那么您可以按照以下解决方案使用executeScript() 方法:

    • Java解决方案:

      WebElement myElement = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@class='table table-hover']//tbody/tr/td")));
      String myText = ((JavascriptExecutor)driver).executeScript('return arguments[0].childNodes[2].textContent;', myElement).toString();
      

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签