java - 如何在 Java 中使用 Selenium 获取 div 内的 anchor 标记 href 和 anchor 标记文本

标签 java selenium selenium-webdriver chrome-web-driver

我的 HTML 代码由多个 div 组成。每个 div 内都有一个 anchor 标记列表。我需要获取 子容器 div 中 anchor 标记的 href 值和文本值。我正在使用 Selenium 来获取网页的 HTML 代码。

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代码:

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

输出:

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

我需要的输出:

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

最佳答案

试试这个,

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());
        }

关于java - 如何在 Java 中使用 Selenium 获取 div 内的 anchor 标记 href 和 anchor 标记文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40624536/

相关文章:

java - 为什么 WebElement 对于每个循环使用相同的 Selenium?

java - 如何使用 Selenium 和 Java 在网页中定位 <image> 标签

java - 通过 Selenium 删除 cookie

python - 检索当前运行的测试用例的名称

java - Selenium 页面对象重用

java - 如何使用 actions 类在相邻窗口或选项卡中打开链接(右键单击 element->sendkeys ArrowDown ->sendkeys Enter)

java - lighttpd : redirecting to another page causes duplicated hostname in path

java - 限制我的方法的执行时间

java - 如何在 Hibernate Criteria Query 中使用 MySQL 函数

java - 将 6 个月前的日期转换为字符串