selenium webdriver找到锚标签并单击它

Sat*_*k k 13 java selenium web-scraping web-scripting

<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>
Run Code Online (Sandbox Code Playgroud)

在这里我需要找到并使用Selenium api 点击关于链接,但我无法做到.

我做的是

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();
Run Code Online (Sandbox Code Playgroud)

但它不起作用

dev*_*snd 23

根据我的经验,Selenium API以这种方式存在许多缺陷.它们大多只能通过重新选择你的选择器来克服.例如,您可以尝试使用XPath选择器来获取元素:

driver.findElement(By.xpath("//a[contains(.,'About')]")).click();
Run Code Online (Sandbox Code Playgroud)

此外,如果您尝试使用Internet Explorer,则可能有助于不单击该元素,而是模拟按Enter按钮.所以找到元素,你可以试试这个:

driver.findElement(By.linkText("About")).sendKeys(Keys.ENTER);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我按你的建议改进了我的答案. (2认同)