Posting Status in Facebook using Selenium and Java - java

How to Post Status in Facebook using Selenium and Java?I have tried below code which doesn't work.Able to login but getting error no such element while posting status.After login i am getting notification popup allow or block,how to handle this popup also? Below the code i am using for testing this.
public class NewTest {
private WebDriver driver;
#Test
public void testEasy() throws InterruptedException {
driver.get("https://www.facebook.com/");
Thread.sleep(5000);
driver.findElement(By.id("email")).sendKeys("email");
driver.findElement(By.id("pass")).sendKeys("password" + Keys.ENTER);
Thread.sleep(5000);
driver.findElement(By.xpath("//textarea[#title=\"What's on your mind?\"]")).click();
driver.findElement(By.xpath("//textarea[#title=\"What's on your mind?\"]")).sendKeys("Hello World");
driver.findElement(By.xpath("//textarea[#title=\"What's on your mind?\"]")).sendKeys(Keys.ENTER);
}
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\admin\\Desktop\\Test\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}
#AfterTest
public void afterTest() {
driver.quit();
}
}

Your XPath expression is not very correct, as far as I can see thte title of the relevant textarea looks like:
What's on your mind, user1984
so you need to amend your locator to use XPath contains() function like:
By.xpath("//textarea[contains(#title,\"What's on your mind\")]")
Using Thread.sleep is a performance anti-pattern, you should be using WebDriverWait instead. Example refactored code:
driver.get("https://www.facebook.com/");
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.elementToBeClickable(By.id("email"))).sendKeys("email");
wait.until(ExpectedConditions.elementToBeClickable(By.id("pass"))).sendKeys("password" + Keys.ENTER);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//textarea[contains(#title,\"What's on your mind\")]"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//textarea[contains(#title,\"What's on your mind\")]"))).sendKeys("Hello World");

Related

Not able to identify an element in Selenium Webdriver (cookies pop-up on skynews)

I have tried all the methods including xpath but I am still not able to click on the Accept button on cookies popup on https://www.news.sky.com
Tried css selector, xpath, frame etc everything.
Here is my code:
public class Browser {
WebDriver driver;
public void browser_open() {
String projectPath = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver", projectPath+"\\Drivers\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
}
public void navigate() throws InterruptedException {
driver.get("http://news.sky.com");
//Thread.sleep(5000);
driver.switchTo().frame("sp_message_iframe_368417");
driver.findElement(By.xpath("/html/body/div/div[3]/div[3]/button[1]")).click();
}
}
Please can someone help me on this?
I have already gone through a lot of posts on this and other forums but couldn't find an solution.
Thanks
I would suggest the xpath of //button[#title='Accept'] for what it's worth.
It's possible the switch to doesn't work because the element doesn't exist yet in the frame.
driver.switchTo().frame("sp_message_iframe_368417");
WebDriverWait wait = new WebDriverWait(driver, 10000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[#title='Accept']")));
driver.findElement(By.xpath("//button[#title='Accept']")).click();

How do I create Page Object Model that works for Android AND iOS in Appium Java

I have created a Page Object in Java with Appium and Selenium that is currently working for an Android app as shown below:
public class MattVerifyPage extends PageObject{
private AppiumDriver driver = FrameworkInitialize.driver;
By verifyTitle = By.xpath("/hierarchy/android.widget.TextView");
public void verifyTitle(String expectedTitle){
String actualTitle = driver.findElement(verifyTitle).getText();
However, I need it to work an the Android app and the iOS app, the xpath selector is different for both apps. I think I need to do something like this:
#AndroidFindBy(xpath = “androidxpath”)
#iOSFindBy(xpath = “iOSxpath”)
public MobileElement verifyTitle ;
This would mean regardless of whether I am using Android or iOS I would still just use the one variable called 'verifyTitle'.
However, when I do this, the driver.findElement line (String actualTitle = driver.findElement(verifyTitle).getText() shows the following error:
findElement
(org.openqa.selenium.By)
in DefaultGenericMobileDriver cannot be applied
to
(io.appium.java_client.MobileElement)
I think I am comparing AppiumElements with SeleniumElements but I’m not sure how to resolve it.
Any help would be greatly appreciated.
Thanks
Matt
Yes, lots of mixing of object types in your original example. You're on the right track with the #OSFindBy annotations. Once you have those defined you already have the element so no need to find it again. The following would be all you'd need:
verifyTitle.getText()
See this blog post for more information on the Page Object Model (POM).
Summary:
import all the good stuff including PageFactory;
public class YourPage {
private WebDriver driver;
public YourPage(AppiumDriver<MobileElement> driver) {
this.driver = driver;
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
}
#AndroidFindBy(id = "android_button")
#iOSFindBy(id = "ios_button")
private MobileElement that_button;
public void pushTheButton() {
that_button.click()
}
}
Note: above code is untested / written off the top of my head / I don't write Java for a living. Prone to error, but should give you the idea.
This Working with Me, My Project Selenium, TestNG and Appium use PageFactory.initElements
public class Login extends Setup {
#Test
public void loginAlert() throws InterruptedException {
Button button = new Button(driver);
PageFactory.initElements(driver, button);
Input input = new Input(driver);
PageFactory.initElements(driver, input);
Input input1 = new Input(driver);
System.out.println("Test Alert Login");
button.ById("navigation_more");
button.ById("btnLogin");
input.ById("et_email_or_phone_number", "dikakoko.com");
input1.ById("tet_password", "dikakoko");
}
}
Below this is the function I called above.
public class Input {
AppiumDriver<MobileElement> driver;
Root root = new Root();
public Input(AppiumDriver<MobileElement> driver) {
this.driver = driver;
}
public void ById(String selector, String textValue) {
MobileElement element = driver.findElement(By.id(root.element() + ":id/" + selector));
waitForVisible(driver, element);
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.sendKeys(textValue);
actions.build().perform();
System.out.println("Input: " + textValue);
}
private void waitForVisible(AppiumDriver<MobileElement> driver, MobileElement element) {
try {
Thread.sleep(5000);
System.out.println("Waiting for element visibility");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOf(element));
} catch (Exception e) {
e.printStackTrace();
}
}
}
and This
public class Button {
AppiumDriver<MobileElement> driver;
Root root = new Root();
public Button(AppiumDriver<MobileElement> driver) {
this.driver = driver;
}
public void ById(String selector) {
MobileElement element = driver.findElement(By.id(root.element() + ":id/" + selector));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.build().perform();
System.out.println("Button is Clicked!");
}
}
I Use This
Button button = new Button(driver);
PageFactory.initElements(driver, button);
Input input = new Input(driver);
PageFactory.initElements(driver, input);
My References : From www.seleniumeasy.com

Selenium testing on Frames

I am trying to learn Selenium from Youtube. I have written the simple code below on Frames. I want to click on linkText which is not visible but manually can scroll and click on it. I am trying with the below code but getting the error:
org.openqa.selenium.WebDriverException: unknown error: Element is not clickable
My code:
public class Frame_Test {
WebDriver driver;
#Test
public void test1() {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html");
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.switchTo().frame("packageListFrame");
driver.findElement(By.linkText("org.openqa.selenium.safari")).click();
}
}
You can scroll down with screen height using this code:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
Scrolling down for some number of pixels:
js.executeScript("scroll(0, 300);");
Scrolling up for some number of pixels:
js.executeScript("scroll(0, -300);");
Hope it helps you!
You can use the below method:
public static void scrollToElement(By elementToken, WebDriver driver){
WebElement element = driver.findElement(elementToken);
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Or if you don't want to use the explicit method you can use the scroll code in your code:
driver.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html";
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.switchTo().frame("packageListFrame");
WebElement element = driver.findElement(By.linkText("org.openqa.selenium.safari"));((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
driver.findElement(By.linkText("org.openqa.selenium.safari")).click();

Cannot handle popup newsletter

I am trying to test an E-Commerce website using Selenium webdriver. The problem in the test is that whenever I try to add stuff in the cart it just pops a news letter window which I tried handling using alert but I cannot.
Can someone please help me. I am attaching a screenshot below along with the code.
public class Ui {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","C:/New folder/geckodriver.exe");
//First Iam going to initialize the webdriver by using Firefox driver//
WebDriver driver = new FirefoxDriver();
driver.get("https://www.build.com/");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='search_txt']")).sendKeys("K-6626-6U ");
Actions enter = new Actions(driver);
enter.moveToElement(driver.findElement(By.xpath(".//*[#id='site-search']/div/button"))).click().build().perform();
}
}
First thing is - Its not an alert it a window popup So you need to locate the close button and then click
Use below code for the same :
public class Ui
{
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver","C:/New folder/geckodriver.exe");
//First Iam going to initialize the webdriver by using Firefox driver//
WebDriver driver = new FirefoxDriver();
driver.get("https://www.build.com/");
driver.manage().window().maximize();
new WebDriverWait(driver, 60).until(ExpectedConditions.visibilityOf( driver.findElement(By.xpath("//button[#class='close external-close']")))).click();
}
}
Here you have to use ExplicitWait until popup get visible and then have to perform click. If you won't use the wait then it will throw ElementNotVisibleException.
wait for some time and click on escape
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.build.com/");
driver.manage().window().maximize();
//give own time
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Actions enter = new Actions(driver);
enter.sendKeys(Keys.ESCAPE).perform();
}

The selenium webdriver always pickup the second result from google search suggestion

Use below simple test code but selenium always like to choose second google suggestion result as the search text:
For example:
I input "Selenium", google will give suggestion list like below:
Selenium
Selenium WebDriver
Then webdriver will always pick up "Selenium WebDriver". But I used webdriver to sendKeys as "Selenium".
Is it a bug to webdriver?
public class HelloWorld {
private WebDriver driver;
#Before
public void setUp() {
System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(caps);
driver.get("http://www.google.com");
}
#After
public void tearDown() {
driver.quit();
}
#Test
public void testLitianyiNewsIsExisting() throws InterruptedException {
WebElement inputField = driver.findElement(By.name("q"));
inputField.sendKeys("selenium");
//Thread.sleep(5000);
driver.findElement(By.name("btnK")).submit();
}
}
I'm pretty sure googles immediate results are bugging you here. Once you are halfway typing your query, Google will start showing you the results already and the "btnK" button will no longer be visible. Try this in stead:
#Test
public void testLitianyiNewsIsExisting() throws InterruptedException {
WebElement inputField = driver.findElement(By.name("q"));
inputField.sendKeys("selenium");
inputField.sendKeys(Keys.ENTER);
}

Categories

Resources