简体   繁体   English

如何在Java中使用Selenium在div中获取锚标记href和锚标记文本

[英]How to get anchor tag href and anchor tag text inside a div using Selenium in Java

My HTML code consists of multiple div s. 我的HTML代码由多个div组成。 Inside each div is a list of anchor tags. 每个div内都有一个定位标记列表。 I need to fetch the href values and text values of the anchor tags that are in the sub-container div . 我需要获取位于sub-container div中的定位标记的href值和文本值。 I'm using Selenium to get the HTML code of the webpage. 我正在使用Selenium来获取网页的HTML代码。

HTML code: HTML代码:

<body>
    <div id="main-container">
        <a href="www.one.com">One</a>
        <a href="www.two.com">Two</a>
        <a href="www.three.com">Three</a>

        <div id="sub-container">
            <a href="www.abc.com">Abc</a>
            <a href="www.xyz.com">Xyz</a>
            <a href="www.pqr.com">Pqr</a>
        </div>
    </div>
</body>

Java code: Java代码:

List<WebElement> list = driver.findElements(By.xpath("//*[@href]"));
for (WebElement element : list) {
    String link = element.getAttribute("href");
    System.out.println(e.getTagName() + "=" + link);
}

Output: 输出:

a=www.one.com
a=www.two.com
a=www.three.com
a=www.abc.com
a=www.xyz.com
a=www.pqr.com

Output I need: 我需要的输出:

a=www.abc.com , Abc
a=www.xyz.com , Xyz
a=www.pqr.com , Pqr

Try this, 尝试这个,

List<WebElement> list = driver.findElements(By.xpath("//div[@id='sub-container']/*[@href]"));
        for (WebElement element : list) {
            String link = element.getAttribute("href");
            System.out.println(element.getTagName() + "=" + link +", "+ element.getText());
        }

You can use element.getText() to get the link text. 您可以使用element.getText()获取链接文本。

If you only want to select the links in the sub-container, you can adjust your xPath: 如果只想选择子容器中的链接,则可以调整xPath:

//*[@id="sub-container"]/a

Pretty simple, try as below: 非常简单,请尝试以下操作:

 `List<WebElement> list = driver.findElements(By.xpath("//div[@id='sub-container']/a"));
    for (WebElement element : list) {
        String link = element.getAttribute("href");
        String text = element.getText();
        System.out.println(e.getTagName() + "=" + link + ", " + text);
    }

if id sub-container is unique, just use the below line 如果id子容器是唯一的,请使用以下行

driver.findElements(By.cssSelector("div#sub-container>a"));

thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM