如何使用Selenium WebDriver在鼠标悬停时获取工具提示文本

7
我无法在鼠标悬停在工具提示图标之后获取工具提示文本。我需要获取工具提示文本,这是HTML代码。
<a class="tooltip" onclick="SocialAuth.showOpenIDLoginWindow('google');_gaq.push(['_trackEvent','LoginForm','google-login','google login was clicked']);" href="javascript:void(0);"><span>We dont store your password or access your contacts on your Google account.</span><img class="social" height="39" width="40" src="/images/login/google.png"/>

我之前回答过类似的问题,你可以在这里查看:https://dev59.com/knLYa4cB1Zd3GeqPXm18 。我相信,在Selenium中你也可以做类似的事情。 - MervS
Webdriver 返回了什么错误? - Castilho
尝试在整个源代码中寻找工具提示。它可能在其他地方。 - mm_
请发送您想要爬取的网站。 - mm_
3个回答

2
从工具提示中获取文本的方法在Jquery ToolTip上与HTML有所不同。当使用Jquery ToolTip时,getAttribute()无法正常工作。如果您查看http://demoqa.com/tooltip/上的工具提示示例,则为Jquery工具提示。

以下代码在此处有效:

    WebDriver driver=new FirefoxDriver();
    driver.get("http://demoqa.com/tooltip/");
    WebElement element = driver.findElement(By.xpath(".//*[@id='age']"));
    Actions toolAct = new Actions(driver);
    toolAct.moveToElement(element).build().perform();
    WebElement toolTipElement = driver.findElement(By.cssSelector(".ui-tooltip"));
    String toolTipText = toolTipElement.getText();
    System.out.println(toolTipText);

一个很好的参考是: http://www.seleniumeasy.com/selenium-tutorials/how-to-verify-tooltip-text-with-selenium-webdriver-using-java 该链接介绍了如何使用Java和Selenium WebDriver验证工具提示文本。

2
使用下面的代码行从元素中获取工具提示文本。
String toolTipText = driver.findElement(By.id(element's id)).getAttribute("title");

尝试使用以下代码:driver.findElement(By.class(tooltip)).getAttribute("span"); - HemChe
实际上,我有三个具有相同类名和CSS选择器的图标,因此它无法在图标本身上进行鼠标悬停。 - Raghu
1
然后,请尝试在xpath中使用position()函数。尝试以下代码。 By.xpath("//a[@class='tooltip'] and [position()=2]").getAttribute("span"); - HemChe

1
你需要使用Actions来完成这个操作。在这个示例中,我打印了Google上的鼠标悬停消息。
    Actions ToolTip1 = new Actions(driver);
    WebElement googleLogo = driver.findElement(By.xpath("//div[@id='hplogo']"));

    Thread.sleep(2000);

    ToolTip1.clickAndHold(googleLogo).perform();

使用“clickAndHold”方法执行鼠标悬停操作。
使用“getAttribute”命令获取工具提示的值。
    String ToolTipText = googleLogo.getAttribute("title");

    Assert.assertEquals(ToolTipText, "Google");

    Thread.sleep(2000);
    System.out.println("Tooltip value is: " + ToolTipText);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接