如何使用selenium基于其href属性选择页面中的链接?

时间:2013-10-25 06:02:06

标签: java eclipse selenium-webdriver

我是硒的新手。 我正在尝试根据" href"选择一个链接。属性。我不能在这里使用xpath,因为每次页面加载时链接都会在页面周围移动。请帮我。 谢谢。

4 个答案:

答案 0 :(得分:1)

使用xpath // a [contains(@ href,'yourhref')]和by.xpath或类似的css。使用//时,它表示相对xpath,因此无论层次结构如何,如果您的href是唯一的,这将为您完成工作。

答案 1 :(得分:0)

您可以使用By.linkTextBy.partialLinkText,例如

<a href="http://www.google.com/search?q=cheese">search for cheese</a>>

WebElement cheese = driver.findElement(By.partialLinkText("cheese"));

此示例已从here

中提取

答案 2 :(得分:0)

您可以使用this xpath构造方法或以下方法。

public void clickLink(WebDriver driver) {

    List<WebElement> aList = driver.findElements(By.tagName("a"));

    for (WebElement el : aList) {

        // if (el.getAttribute("href").contains("your href partial value")

        if (el.getAttribute("href")
                .equalsIgnoreCase("your full hreff text")) {
            el.click();
            break;
        }
    }
}

根据您的要求使用if条件。部分或全部比较。

答案 3 :(得分:0)

使用CSS Selector,example- driver.findElement(By.cssSelector(“a [href =(your href)]”)