Can I get working code for Facebook logout? - facebook

I am not able to find the correct XPath for clicking on Logout in Facebook.
I have been trying for so long to take XPath to click on Logout.
Can anyone please help me out to click on Logout using selenium webdriver with java.
Code trials:
//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();

Are you getting any exception ? like NosuchElement exception or element not found error something like that.
If so, you could wait until the element is visible and then you have to perform the operation.
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();
}
}

To click on the element with text as Logout you need to use WebDriverWait for the element to be clickable and you can use the following lines of code:
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();

Related

How can i handle popups in playwright-java?

How can i handle alerts and popups in playwright-java?
there are different methods in API like page.onDialog(), page.onPopup(), what is the difference between them and how can i generate a handle?
//code to launch my browser and url
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new LaunchOptions().withHeadless(false).withSlowMo(50));
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("http://myurl.com");
//had to switch to iframe to click on upload button
Frame mypage = page.frameByName("uploadScreenPage");
//below line is triggering the alert
mypage.setInputFiles("//*[#id='fileUpload']",Path.of("C:\\myFile.jar"));
//using this code to handle alert, which is not working
page.onDialog(dialog -> {dialog.accept();});
unable to accept alert using the above code. also alert has occurred after clicking an element that is inside an iframe. how can i handle such alerts?
Dialogs are messages like an alert or a confirm, whereas popups are new pages, like the one you would get by calling window.open.
This is how you can use it :
page.onDialog(dialog -> {
assertEquals("alert", dialog.type());
assertEquals("", dialog.defaultValue());
assertEquals("yo", dialog.message());
dialog.accept();
});
page.evaluate("alert('yo')");
I am happy to answer this question. I encountered the same situation and find the solution. Please see below:
//Handling Pop-up or new page
Page pgdriver1 = pagedriver.waitForPopup(new Runnable()
{
public void run() {
pagedriver.click("text=\"Analiza\"");
}
});
pgdriver1.click("//button[normalize-space(#aria-label)=\"Close dialog\"]/nx-icon");
I hope this answer your question.
//listening to the alert
page.onDialog(dialog -> {dialog.accept();});
//next line will be action that triggers your alert
page.click("//['clickonsomethingthatopensalert']")

How to write selenium webdriver automation script for Facebook logout?

I tried this code. Its automating the browser, logging in successfully but I'm not able to logout successfully. Please Help.
public class fb {
public static void main(String args[])
{
WebDriver driver = new FirefoxDriver();
driver.get("https://facebook.com");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("your email");
driver.findElement(By.xpath(".//*[#id='pass']")).sendKeys("your password");
driver.findElement(By.xpath(".//*[#id='u_0_n']")).click();
driver.findElement(By.xpath(".//*[#id='userNavigationLabel']")).click();
driver.findElement(By.id("u_7_2")).click();// for logout-> button.But not working.
Automation Script for FaceBook Login and logout:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("your email");
driver.findElement(By.xpath(".//*[#id='pass']")).sendKeys("your password");
//click for login
driver.findElement(By.xpath("//label[#id='loginbutton']/input")).click();
//Mouse over on logOut drop down menu icon,then click logout
WebElement mouseOverEle = driver.findElement(By.id("pageLoginAnchor"));
Actions actions = new Actions(driver);
actions.moveToElement(mouseOverEle).click().perform();
//click for logout
driver.findElement(By.xpath("//input[#value='Log Out']")).click();
Try Using the below code to click on the log out button
//wait for the userNavigationLabel to load fully any wait techniques implicit or explicit for sample i have used Thread.sleep although it is not recommended
Thread.sleep(3000);
JavascriptExecutor js = (JavascriptExecutor) driver;
String script = "var forms = document.getElementsByTagName('form');for (var i = 0; i < forms.length; i++) { if(forms[i].getAttribute('action')=='https://www.facebook.com/logout.php'){forms[i].submit();}}";
js.executeScript(script);
In the above code i have used javascript to click on the logout button...i tested it on the browser console it is working fine
Hope this helps you.....Kindly get back if you have any queries
try:
lsb=browser.find_element_by_xpath('//*[#id="pageLoginAnchor"]')
lsb.click()
time.sleep(5)
mlb=browser.find_element_by_xpath('//*[#id="u_d_3"]/div/div/div[1]/div/div/ul/li[16]')
time.sleep(2)
mlb.click()
inputElement33 = browser.find_element_by_name('pass').is_displayed()
print("Looged out")
except:
print("Cannot logout")
// Enter you Email id
dr.findElement(By.xpath(".//*[#id='email']")).sendKeys("YorEmailID");
// Enter you Password
dr.findElement(By.xpath(".//*[#id='pass']")).sendKeys("YourPassword");
//click for login
dr.findElement(By.xpath("//label[#id='loginbutton']/input")).click();
dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Click for Alert
dr.findElement(By.className("_3ixn")).click();
//Click for Navigation Label
dr.findElement(By.xpath(".//*[#id='userNavigationLabel']")).click();
dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Click for Lout Button
dr.findElement(By.xpath("//a[contains(#data-gt,'menu_logout')]")).click();
Replace your logout button click with this.
//Wait for button appear
WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(4));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[.='Log out']")));
//Click it by xpath
driver.FindElement(By.XPath("//a[.='Log out']")).Click();
Or:
//Wait for button appear
WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(4));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[.='Log out']")));
//Click it by JS
IJavaScriptExecutor js = ((IJavaScriptExecutor)driver);
IWebElement logout = driver.FindElement(By.XPath("//a[.='Log out']"));
js.ExecuteScript("arguments[0].click();", logout);
100% worked
**#Working script**
**#firefox can be used too instead of chrome**
**#sleep is necessary to give sufficient loading time**
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import NoSuchElementException
usr=input('Enter Email Id:')
pwd=input('Enter Password:')
driver = webdriver.Chrome()
driver.get('https://www.facebook.com/')
a = driver.find_element_by_id('email')
a.send_keys(usr)
b = driver.find_element_by_id('pass')
b.send_keys(pwd)
c = driver.find_element_by_id('loginbutton')
c.click()
sleep(20)
d= driver.find_element_by_id("userNavigationLabel")
d.click()
sleep(10)
e=driver.find_element_by_xpath("//a[contains(#data-gt,'menu_logout')]")
e.click()
sleep(5)
driver.quit()
There are duplicate objects in the Home page.Hence, to avoid confusion,Xpath can be written in combination of class names, which in our case is,
//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li
Get the maximum number of <li> tags in the <ul> as follows ,
List<WebElement> li = driver.findElements(By.xpath("//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li"));
System.out.println("Size:"+li.size());
The Log out button will always be the last option, inspite of any changes to the list , hence append the last index to the xpath and click on it ,
String logOutBtn = "//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li[" + li.size() + "]";
driver.findElement(By.xpath(logOutBtn)).click(); -- Clicking on log out button
Hope this helps ! Thank you ..
package package1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class class1 {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\CloudLogic.Tech01\\Desktop\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver drr = new ChromeDriver();
drr.get("https://www.facebook.com/");
drr.findElement(By.id("email")).sendKeys("emailId");
drr.findElement(By.id("pass")).sendKeys("********");
drr.findElement(By.xpath("//label[#id='loginbutton']")).click();
}
}

How to close Dialog that uses AbstractDialogAction

I am working on Netbeans building a JavaFX application.
I started using ControlsFX (http://fxexperience.com/controlsfx/)
I have implemented a simple Dialog that uses custom AbstractDialogAction s as I want specific number of buttons to appear.
I do this like this:
Action a = new AbstractDialogAction(" button a ", Dialog.ActionTrait.CLOSING) {
#Override
public void execute(ActionEvent ae) {
}
};
ArrayList<Action> actions = new ArrayList<>();
actions.add(a);
actions.add(b); // other button
actions.add(c); // another button
dialog.actions(actions);
Action response = dialog.showConfirm();
Dialog is shown correctly with the given buttons.
My question is how to force the Dialog to close when a button is pressed ?
I thought setting a Dialog.ActionTrait.CLOSING would do the trick, but the Dialog stays open.
From eugener in ControlsFX mailing list
public void execute(ActionEvent ae) {
if (ae.getSource() instanceof Dialog ) {
((Dialog) ae.getSource()).setResult(this);
}
}
The above sets the result of the Dialog to be the current Action and closes the Dialog
But maybe that is a little redundant as I can simply call:
((Dialog) ae.getSource()).hide();
.hide() hides the Dialog and also sets the current action as the result.
I can't suggest which is a better solution (hide() was suggested by jewelsea)
In addition I would suggest to always override the toString() method of class AbstractDialogAction, in order to get readable result from:
Action response = dialog.showConfirm();
System.out.println("RESPONSE = "+ response.toString());
Hide the dialog to close it => dialog.hide()

Hide Dialog from inside in LWUIT

I have created a Dialog with two buttons Yes, No, and then I have add action listener to them, my problem is that I want no button to hide the Dialog that I have created
the code is looks like:
dialog = new Dialog(title);
dialog.setDialogType(Dialog.TYPE_CONFIRMATION);
ta = new TextArea(text);
ta.getStyle().setBorder(Border.createEmpty());
ta.setEditable(false);
yesCommand = new Button("YES");
noCommand = new Button("NO");
yesCommand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
LGBMainMidlet.getLGBMidlet().notifyDestroyed();
}
});
noCommand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Logger.Log("Bye Bye");
dialog = null;
System.gc();
}
});
dialog.addComponent(ta);
dialog.addComponent(yesCommand);
dialog.addComponent(noCommand);
dialog.show();
the code is not working for me, can anyone told me what is the problem?
B.N. I have used dialog.dispose(), but it exit the whole application
It is better to use
dialog.setTimeout(1000); the number show the time limit the dialog box wait in milliseconds. So by doing this you can exit the dialog form automatically.
Dialog.dispose() does not exit the whole application, it just closes the dialog.
If you have nothing in your application you might see nothing if you dispose the dialog.

Ajax Modal Popup Display Issue

On the web page, there is gridview control contains product ID's. bind to a link button.
On ItemCommand event of gridview, I fetch the product information and display in the ajax modal popup extender control. The popup is programatically show on ItemCommand of gridview and also hide programatically.
Now the problem is that, when i close popup after showing first product details and try to see next 1 by clicking on other product ID.., sometimes details are displaye dand sometimes not.
The data comes from database is fetched as well for each product.
Plz help.
I do the same but i have no such problem. So i am pasting code here that may b help full to u.
CODE:
protected void GVallusers_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
GridViewRow gvRow = ((GridView)sender).Rows[e.NewEditIndex];
populatepanel(gvRow);
ModalPopupExtender1.Show();
}
catch (Exception exc)
{
lblinfo.Text = exc.Message;
}
}
public void populatepanel(GridViewRow gvrow)
{
string userid = gvrow.Cells[0].Text;
lblSite.Text=gvrow.Cells[1].Text;
lblemail.Text = gvrow.Cells[3].Text;
}