如何从字符串中只提取数字

How to extract only number from string

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

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

要提取和打印 prices 修剪 non-ASCII 字符,您可以使用 replaceAll("[^\p{ASCII}]", "") 并使用 Java8 的 stream() and map() you can use either of the following :

  • 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]
    

参考资料

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

  • How to print all the button texts within the url using Selenium through Java