Ami
Ami

Reputation: 111

How to locate multiple attribute/tags present under single tag with xpath

Please refer to this sample code:

<div class="menu"> 
    <a href="one.html">One</a>
    <a href="two.html">Two</a>
    <button type="button">Three</button>
    <button type="button">Four</button>
        <div class="menu2">
            <a href="five.html">Five</a>
            <a href="six.html">Six</a>  
        </div>
        <div class="menu3">
            <a href="seven.html">Seven</a>
            <button type="button">Eight</button>
        </div>
</div>

I am trying to locate 'a' tag and 'button' tag using single xpath.

I can do it using cssSelector with following code:

List<WebElement> list = d.findElements(By.cssSelector("div[class='menu'] a, div[class='menu'] button"));

for (WebElement l: list) {
System.out.println(l.getText());
}

But I would like do it with xpath.

Upvotes: 2

Views: 1476

Answers (2)

user8648665
user8648665

Reputation: 1

You can also use Jsoup to get all the data.Here I have some example:

Document doc = Jsoup.parse(content);
Elements elements = doc.select("div.menu a");
for (Element element : elements) {
  String url = element.attr("href");
}

Upvotes: 0

Andersson
Andersson

Reputation: 52665

Try to use below XPath to match both a and button:

//div[@class="menu"]//*[name()=("a" or "button")]

or

//div[@class="menu"]//*[self::a or self::button]

Upvotes: 2

Related Questions