【问题标题】:Can I get working code for Facebook logout?我可以获得 Facebook 注销的工作代码吗?
【发布时间】:2018-12-20 11:05:35
【问题描述】:
我无法找到在 Facebook 中单击注销的正确 XPath。
我一直在尝试使用 XPath 来单击注销。
任何人都可以帮我点击使用 selenium webdriver 和 java 的 Logout。
代码试验:
//clicking on navigation bar
driver.findElement(By.id("userNavigationLabel")).click();
System.out.println("Successfully clicked");
//Clicking on logout
driver.findElement(By.xpath("//span[contains(text(),'Log out')]")).click();
//closing the current tab
driver.close();
【问题讨论】:
标签:
facebook
selenium-webdriver
webdriver
webdriverwait
【解决方案1】:
你有什么异常吗?像 NosuchElement 异常或 element not found 错误之类的。
如果是这样,您可以等到元素可见,然后您必须执行操作。
public void test_01_Logout()
{
WebDriver driver = new FirefoxDriver();
driver.navigate().to("www.facebook.com");
//Add login code here.
waitForElementInDOM(driver, "//div[@id='userNavigationLabel' and
contains(text(),'Account Settings')]", 15);
driver.findElement(By.xpath("//div[@id='userNavigationLabel' and
contains(text(),'Account Settings')]")).click();
waitForElementInDOM(driver, "//span[@class='54nh' and contains(text(),'Log Out')]",
15);
driver.findElement(By.xpath("//span[@class='54nh' and contains(text(),'Log
Out')]")).click();
}
-------------------------------------------------------------------------------------
public void waitForElementInDOM(WebDriver driver,String elementIdentifier, long
timeOutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier)));
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
}
【解决方案2】:
要单击文本为 Logout 的元素,您需要使用 WebDriverWait 以使 元素可点击,您可以使用以下命令代码行数:
driver.findElement(By.cssSelector("div#userNavigationLabel")).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(@data-gt, 'menu_logout')]/span/span[normalize-space()='Log Out']"))).click();