Search code examples
javaseleniumxpathweb-scrapinghtmlunit-driver

How to find HTML elements that match a certain string, using HtmlUnitDriver with java?


I wuold find all HTML element in a page that math a certain string like, for example, <form action=/ method="GET">, using HtmlUnitDriver (java).

What I would do is a web application, that takes in inputs two parameters:

  • url to search for
  • a pattern

I have this piece of java code:

HtmlUnitDriver browser = new HtmlUnitDriver(true);
browser.get(urlParamter);
List<WebElement> result = //find all HTML elements that match a certain pattern.

Now suppose I'm looking for some elements in this page:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
</head>
<body>
    <form id="form1">
    </form>

    <form id="form2">
    </form>

    <p class="test"></p>
    <p class="test"></p>
</body>
</html>

If I search for the string <form id="form1"> I would get the first form element, instead if I search for <p class="test"> I would get the two paragraph elements. Is it possible? All the suggestions will be appreciated.


Solution

  • Just try using findElements() instead of findElement() with the xpath matching your text. Example below.

    List<WebElement> result = browser.findElements(By.xpath("//[contains(text(),'yourtext')]"));