首页 > 解决方案 > 在 selenium JAVA 中提取文本 br 标签

问题描述

我需要获取文本“Texas-United States”和“Illinois-United States”,以便在字符串匹配后单击文本上方的超链接。我尝试了以下方法,但无法做到。任何人都可以在这里帮忙

findElement(By.xpath("//html/body/font/nobr")).getAttribute("innerHTML")
findElement(By.xpath("//html/body/font/nobr")).getAttribute("textContent")
findElement(By.xpath("//html/body/font/nobr")).getText()
findElement(By.xpath("//html/body/font/nobr/text()[preceding-sibling::br]")).getText()
findElement(By.xpath("//html/body/font/nobr/a[1]")).getText()
findElement(By.xpath("//html/body/font/nobr/a[1][following-sibling::node()[1][self::BR]]")).getAttribute("innerHTML")

下面的 HTML 供参考

<nobr>
    <a target="framedetail" href="DetailServlet?com=s&amp;cname=Bank%20of%20America%2c%20National%20Association" onclick="s_objectID=&quot;https://www.example.com/item1 this.s_oc?this.s_oc(e):true">
        <img src="imgs/brcb.gif" width="8" height="8" alt="Commercial Bank" border="0">
        &nbsp;Bank of America, National Association
    </a>
    <br>
        &nbsp;&nbsp;&nbsp;Texas-United States
    <br>
    <a target="framedetail" href="DetailServlet?com=s&amp;cname=Bank%20of%20America%2c%20National%20Association" onclick="s_objectID=&quot;https://www.example.com/item2 this.s_oc?this.s_oc(e):true">
        <img src="imgs/brcb.gif" width="8" height="8" alt="Commercial Bank" border="0">
        &nbsp;Bank of America, National Association
    </a>
    <br>
        &nbsp;&nbsp;&nbsp;Illinois-United States
    <br>
</nobr>

标签: javaselenium-webdriver

解决方案


如果你想点击前面的链接,你可以使用下面的代码:

findElement(By.xpath("//text()[contains(., 'Texas-United States')]/preceding-sibling::a[1]")).click()

findElement(By.xpath("//text()[contains(., 'Illinois-United States')]/preceding-sibling::a[1]")).click()

推荐阅读