【问题标题】:Scrape all matching contents using XPath function使用 XPath 函数抓取所有匹配的内容
【发布时间】:2017-04-02 05:03:26
【问题描述】:

如何确保我的 selenium 代码抓取 XPath 的所有匹配内容?
请帮助我提出您的想法。

例如,这些是我的 HTML 标签:

<tr class="1" role="r1">
    <td class="c1">
        <a href="www.google.com">
        </a>
    </td>
</tr>
<tr class="2" role="r2">
    <td class="c2">
        <a href="www.youtube.com">
        </a>
    </td>
</tr>
<tr class="3" role="c3">
    <td class="c3">
        <a href="www.facebook.com">
        </a>
    </td>
</tr>

我希望我的 selenium 代码从 href 标记中获取所有链接。
所以,下面是我的 XPath:

String links = driver.findElement(By.xpath("//tr[@role='cad']//td[@class='c1']//a")).getAttribute("href"); 
System.out.println(links);

但它只获取第一个 href 输出,即www.google.com。

想要的输出是:

www.google.com
www.youtube.com
www.facebook.com

我怎样才能做到这一点?
任何数组实现都会是更好的选择?

【问题讨论】:

标签: java selenium xpath selenium-webdriver


【解决方案1】:

试试下面的代码:

 List<WebElement> elements= driver.findElements(By.xpath("//table/tbody/tr"));

    int i =0 ;

    while(i<elements.size()){

        WebElement childElement =  elements.get(i).findElement(By.cssSelector("a"));

    System.out.println(childElement.getAttribute("href"));

    i++;
    }

【讨论】:

  • 美丽;它正在工作..我仍然想知道,这是最有效的解决方案......无论如何,谢谢。
【解决方案2】:

试试下面的代码。

List<WebElement> links = driver.findElements(By.xpath("//tr/td/a"));

    for(int i=0;i<links.size();i++){
        System.out.println(links.get(i).getAttribute("href"));
    }

【讨论】:

  • 您有机会尝试这个解决方案吗?
猜你喜欢
  • 2013-11-14
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2016-01-26
相关资源
最近更新 更多