我可以获取Facebook注销的工作代码吗?

时间:2018-12-20 11:05:36

标签: facebook selenium-webdriver webdriver webdriverwait

我找不到用于在Facebook中单击注销的正确XPath。
我一直在尝试使用XPath来单击Logout。
谁能帮助我,使用带有Java的Selenium Webdriver单击注销。

代码试用:

//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();

2 个答案:

答案 0 :(得分:1)

您有任何例外吗?像NosuchElement异常或找不到元素之类的错误。 如果是这样,则可以等到元素可见后再执行操作。

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();
}           
}

答案 1 :(得分:0)

要单击文本为注销的元素,您需要使用 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();