【问题标题】:How to extract only number from string如何从字符串中仅提取数字
【发布时间】:2021-01-08 21:38:58
【问题描述】:

我尝试从这些页面中提取价格作为美元文本 site

我使用定位器//span[@data-originalprice] 获取硒文本 但仍然不仅是数字,还尝试在 \\$ 上拆分,但没有任何结果 尝试了一些正则表达式text.split("^-?\\d*(\\.\\d+)?$"),但仍然没有。 有什么想法吗?

【问题讨论】:

  • 试试 xpath 为 ("//span[@data-originalprice]/span[2]")[20]

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

要提取和打印 价格 修剪 非 ASCII 字符,您可以使用 replaceAll("[^\\p{ASCII}]", "") 并使用 Java8 的 stream() 和 @ 987654322@你可以使用以下任一Locator Strategies:

  • cssSelector:

    driver.get("https://www.wooloverslondon.com/new-styles?page=1&gender=161&style=77");
    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.associated-product__price p>span"))).stream().map(element->element.getText().replaceAll("[^\\p{ASCII}]", "")).collect(Collectors.toList()));
    
  • xpath:

    driver.get("https://www.wooloverslondon.com/new-styles?page=1&gender=161&style=77");
    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@class='associated-product__price']//p/span"))).stream().map(element->element.getText().replaceAll("[^\\p{ASCII}]", "")).collect(Collectors.toList()));
    
  • 控制台输出:

    [7,035.00, 6,015.00, 6,015.00, 6,015.00, 6,015.00, 6,015.00, 6,015.00, 5,607.00, 5,607.00, 5,607.00, 4,996.00, 7,646.00]
    

参考文献

您可以在以下位置找到一些相关讨论:

【讨论】:

  • 谢谢,但问题是每个元素文本都包含非 ASCII 字符,所以我问如何只提取没有那些非 ASCII 字符的数字
  • @nuzooo 查看更新的答案并让我知道状态。
  • 谢谢,再问一个问题:我看到你减少了所有不可打印的 ASCII 字符,但你是如何替换 ruby​​ 符号的?
  • @nuzooo ruby​​ 符号也是您想要摆脱的非 ASCII 字符。
  • 再次感谢你很棒
猜你喜欢
  • 2021-07-18
  • 2020-08-07
  • 2019-09-14
  • 2015-10-04
  • 2021-11-14
  • 2016-12-13
  • 2019-06-03
  • 1970-01-01
相关资源
最近更新 更多