【问题标题】:Extract a number from a string getting number format exception从字符串中提取数字获取数字格式异常
【发布时间】:2018-12-13 02:45:48
【问题描述】:

我无法从网页即时测试的字符串中获取数值。 我目前正在使用:

String total_points = potential_points.getText();
System.out.println("Potential points are: " + total_points);
int pot_points = Integer.parseInt(total_points);

问题是选择器实际上也返回了两个字符串: “潜力点” “:” “1476”

如何提取 1476 并将其用作 int。我附上了html。

潜力点:1473 条目:免费玩

【问题讨论】:

  • 以文本格式而不是屏幕截图共享 HTML。
  • 添加到主要问题
  • 我看到图片,添加文本格式。
  • 'potential_points' 变量的类型是什么?
  • 它是一个 Webelement,所以我将 Weblement 更改为字符串,然后更改为 int。但由于“潜在品脱”和“:”,它不会更改为 int。我试图删除它们,以便我可以在计算中使用该值。

标签: java selenium user-interface testing automation


【解决方案1】:

您需要使用下面的子字符串方法获取结果

    String total_points = potential_points.getText();
    int startIndex=total_points.indexOf(":")+2;
    int endIndex=total_points.length();
    String result=total_points.substring(startIndex,endIndex);
    int no=Integer.parseInt(result);

将上面的代码简化如下

    String result=total_points.substring(total_points.indexOf(":")+2,total_points.length());
    int no=Integer.parseInt(result);

【讨论】:

  • 对不起,我实际上只是更改了上面的代码,所以当我使用 potential_points.getText();它返回“潜在点”“:”“1476”。字符串总分是 Potential Points:1476 (或任何值,因为它每次运行都会改变)然后它不会因为两个字符串而变为 int。
  • 我已将 temp 更改为“total_points”。因此,您可以使用上述逻辑单独提取所需的 no。如果要将其转换为 int,则进行解析,否则单独保留子字符串
  • @Subburaj :这样的东西会更有益: string s = (string)((IJavaScriptExecutor)Driver).ExecuteScript("return arguments[0].nextSibling.textContent;", e);
  • 即使每次运行的值都会发生变化,格式也会像“潜在点”“:”“>”对吗?
  • @Subburaj :这两个是 textNodes ,javascript 执行器提供了更有益和可读的格式。我想给出答案,但 OP 拒绝以文本格式共享代码,所以不值得 IMO。
猜你喜欢
  • 2023-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
相关资源
最近更新 更多