selenium webdriver to find the anchor tag and clic

2019-02-08 14:05发布

<div id="ContentPrimary">
<ul class="selectors modeSelectors">
    <li><a href="/content/l411846326l1213g/references/" title="">
        <span class="selector">References (27)</span></a></li>
    <li><a href="/content/l411846326l1213g/referrers/" title="">
        <span class="selector">Cited By (2)</span></a></li>
    <li><a href="/content/l411846326l1213g/export-citation/" title="">
        <span class="selector">Export Citation</span></a></li>
    <li><a href="/content/l411846326l1213g/about/" title="">
        <span class="selector">About</span></a></li>
</ul>

In this I need to find and click About link using Selenium api but I was unable to do it.

what I did is

wait.until(new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver webDriver) {
        System.out.println("Searching ...");
        String s = driver.findElement(By.cssSelector("#ContentPrimary ul li[4] span.selector")).getText();
        System.out.println(s);
        if (Pattern.compile(Pattern.quote("About"), Pattern.CASE_INSENSITIVE).matcher(s).find()) {
            return true;
        } else {
            return false;
        }
    }
});
driver.findElement(By.linkText("About")).click();

but its not working

2条回答
仙女界的扛把子
2楼-- · 2019-02-08 14:49

You can use ExpectedConditions:

wait.until(visibilityOfElementLocated(By.linkText("About"))).click();
查看更多
来,给爷笑一个
3楼-- · 2019-02-08 14:50

In my experience the Selenium API has many flaws in that way. They can mostly only be overcome by reformulating your selectors. For example you could try using a XPath selector to get your element:

driver.findElement(By.xpath("//a[contains(.,'About')]")).click();

Also, if you are trying to use the Internet Explorer it might help not to click the element, but instead to simulate pushing the Enter button. So assumung the Element is found, you could try this:

driver.findElement(By.linkText("About")).sendKeys(Keys.ENTER);
查看更多
登录 后发表回答