So I want to automate youtube videos. so list of API available and also selenium have support for flash objects. My worry is that how can I check video is playing?. Like if I can perform motion detect on video I can pass or fail script accordingly. so can we achieve similar using selenium? or selenium have different approach to do this. Many thanks
I would check that when they click on the 'play' button it changes to the 'pause' icon; something like this:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public class Youtube {
public WebDriver driver;
private String url = "https://www.youtube.com/watch?v=MfhjkfocRR0";
public Youtube() {
System.setProperty("webdriver.chrome.driver", "C:\\SeleniumServer\\chromedriver.exe");
driver = new ChromeDriver();
//driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(url);
}
public void waitFor(int wait){
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public boolean isYoutubePlaying(){
try {
//wait 4 secs for Youtube video to load
waitFor(6000);
WebElement playPauseButton=driver.findElements(By.cssSelector("div.ytp-button")).get(0);
//video is not playing here.
if(playPauseButton.getAttribute("aria-label").equals("Play")){
System.out.println("This Youtube video wasn't playing but we clicked on it to play the video.");
//so we click on the play button to play the video then we return true;
playPauseButton.click();
return true;
}else{
//video should be playing but let's double-check
if(playPauseButton.getAttribute("aria-label").equals("Pause")){
System.out.println("Youtube video is already playing.");
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//only return false if either of the 2 cases above fail.
return false;
}
}//end class
And to run this code simply instantiate it like so:
Youtube yt=new Youtube();
yt.isYoutubePlaying();
Related
i am trying to write selenium script which writes pass/fail based on assert.
the problem i am facing here is the assert results are not getting inserted into excel properly. There is some issue with the for loop which i have written. please help me in fixing it.
thanks in advance.
This is the code which i have written
package DDT;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class TestPass extends ExeclUtility
{
WebDriver driver;
Map<String,Object[]> Exp;
#BeforeClass
public void openBrowser()//opening of the browser is done only 1s before executing the test data
{
System.setProperty("webdriver.chrome.driver","C:\\Users\\DELL\\Desktop\\shree\\qsp_java_selenium\\selenium\\selenium_web_driver\\chrome_driver\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("file:///C:/Users/DELL/Desktop/USN%20and%20Sem.html");
}
#Test(dataProvider="TestData")
public void datasend(String username,String phnum,String Exp) throws InterruptedException, RowsExceededException, WriteException
{
WebElement name=driver.findElement(By.id("field1"));
name.clear();
name.sendKeys(username);
WebElement pwd=driver.findElement(By.id("field2"));
pwd.clear();
pwd.sendKeys(phnum);
WebElement but=driver.findElement(By.id("field4"));
but.click();
Alert alert=driver.switchTo().alert();
SoftAssert assertion=new SoftAssert();
for(int i=0;i<6;i++){
try
{
assertion.assertEquals(Exp, alert.getText());// compares the expected result in excel v/s the actual o/p
Testcase="pass";
Label l3=new Label(3,i,Testcase);
writablesh.addCell(l3);
}
catch(Exception e)
{
Testcase="fail";
Label l3=new Label(3,i,Testcase);
writablesh.addCell(l3);
}}
assertion.assertEquals(Exp, alert.getText());
alert.accept();
assertion.assertAll();
Thread.sleep(3000);
}
#AfterClass
public void closeBrowser()//browser is closed 1s after all the test data are executed
{
driver.quit();
}
#DataProvider(name = "TestData")
public Object[][] ExcelData() throws BiffException, IOException
{
String Filepath="D:\\selenium_pgms\\intern_practice\\Book1.xls";
FileInputStream Excelfile=new FileInputStream(Filepath);
Workbook Exbook=Workbook.getWorkbook(Excelfile);
Sheet Exsheet=Exbook.getSheet("Sheet1");
int Rows=Exsheet.getRows();
int Columns=Exsheet.getColumns();
String Testdata[][]= new String[Rows-1][Columns];
int count=0;
for(int i=1;i<Rows;i++)
{
for(int j=0;j<Columns;j++)
{
Cell Excell = Exsheet.getCell(j,i);
Testdata[count][j]=Excell.getContents();
}
count++;
}
Excelfile.close();
return Testdata;
}
}
I tried below two codes. Both didn't select the "Male" option. Could anyone please let me know where I'm doing a mistake.
It's very difficult to post the code in this site. So many conditions
My code:
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class webelements2 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\rpremala003\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.click();
Select dropdown = new Select (driver.findElement(By.xpath(".//*[#id='Gender']/div")));
dropdown.selectByIndex(1);
}
}
Even I used sendkeys method. But it didn't work for me
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class webelements2 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\rpremala003\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.sendKeys("Male");
google.click();
}
Please suggest me how to overcome this problem
You can use Select() with <select>, <option> elements only. In this current case you can simply click() on drop-down and then click() to choose required option:
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.click();
WebElement option = (driver.findElement(By.xpath("//div[text()='Male']"));
option.click();
You might also need to wait until option to be clickable:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement option = wait.until(elementToBeClickable(By.xpath("//div[text()='Male']")));
option.click();
Simply use this and let me know if it works for you:
For Female
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":e")).click();
For Male
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":f")).click();
For Other
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":g")).click();
For Rather not say
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":h")).click();
And if you need for sign-up gmail, I tried Once:
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
driver.findElement(By.xpath(".//*[#id='FirstName']")).sendKeys("Name");
driver.findElement(By.xpath(".//*[#id='LastName']")).sendKeys("Last name");
driver.findElement(By.xpath(".//*[#id='GmailAddress']")).sendKeys("Email id");
driver.findElement(By.xpath(".//*[#id='Passwd']")).sendKeys("Password");
driver.findElement(By.xpath(".//*[#id='PasswdAgain']")).sendKeys("Password Again");
//Input the month
List<WebElement> month_dropdown = driver.findElements(By.xpath(".//*[#id='BirthMonth']/div"));
//iterate the list and get the expected month
Thread.sleep(3000);
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
Thread.sleep(3000);
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
driver.findElement(By.id("BirthMonth")).click();
driver.findElement(By.id(":3")).click();
driver.findElement(By.xpath(".//*[#id='BirthDay']")).sendKeys("14");
driver.findElement(By.xpath(".//*[#id='BirthYear']")).sendKeys("1988");
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":e")).click();
driver.findElement(By.xpath(".//*[#id='RecoveryPhoneNumber']")).sendKeys("4694222863");
driver.findElement(By.xpath(".//*[#id='RecoveryEmailAddress']")).sendKeys("recovery email id");
driver.findElement(By.id("submitbutton")).click();
Thread.sleep(3000L);
I'm trying to automate Sign In functionality in www.sears.com, but could not recognize the Email text field using the below code
package com.bigbasket.framework.lab;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Sears {
public static void main(String[] args) {
WebDriver browser = new FirefoxDriver();
browser.get("http://www.sears.com/en_us.html");
browser.manage().window().maximize();
browser.findElement(By.xpath("//*[#id='gnf_01_tree_item_5']/span/a")).click();
WebElement currentElement = browser.findElement(By.xpath("//*[#id='myProfiles']/div"));
Actions actions = new Actions(browser);
actions.moveToElement(currentElement).build().perform();
browser.findElement(By.xpath("//*[#id='subnavDD_myProfile']/ul/li[1]/p/a")).click();
try{
WebElement formElement = browser.findElement(By.id("loginFormDisplay"));
currentElement = formElement.findElement(By.xpath("//*[#id='email']"));
}catch(Exception e){
System.out.println(e.getMessage());
}
WebDriverWait wait = new WebDriverWait(browser, 30);
wait.until(ExpectedConditions.visibilityOf(currentElement));
currentElement.sendKeys("srinimarva#gmail.com");
browser.quit();
}
}
Could you please help me in resolving this? Apologize I'm an amateur in Selenium WebDriver for asking a silly question.
your email field is in iframe so to access it you need to switch to frame first, following is the working code for your issue :
WebDriver browser = new FirefoxDriver();
browser.get("http://www.sears.com/en_us.html");
browser.findElement(By.xpath("//*[#id='gnf_01_tree_item_5']/span/a")).click();
WebElement currentElement = browser.findElement(By.xpath("//*[#id='myProfiles']/div"));
Actions actions = new Actions(browser);
actions.moveToElement(currentElement).build().perform();
WebDriverWait wait = new WebDriverWait(browser, 10);
wait.until(ExpectedConditions.visibilityOf(browser.findElement(By.xpath(".//*[#id='subnavDD_myProfile']/ul/li[1]/p/a"))));
browser.findElement(By.xpath(".//*[#id='subnavDD_myProfile']/ul/li[1]/p/a")).click();
try{
WebElement frameElement = browser.findElement(By.xpath(".//iframe[contains(#name, 'easyXDM_default')]"));
browser.switchTo().frame(frameElement);
}
catch(Exception e){
System.out.println(e.getMessage());
}
browser.findElement(By.name("email")).sendKeys("srinimarva#gmail.com");
browser.quit();
I am a newbie to selenium testing.
Basically,
I have a selenium class like :
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import java.awt.AWTException;
import java.awt.Robot;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTests {
public void commonFunction(){
System.setProperty("webdriver.chrome.driver", "C://Downloads//chromedriver_win32//chromedriver.exe");
WebDriver driver = new ChromeDriver();
Actions builder = new Actions(driver);
driver.get("http://localhost:3000");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
test1(driver,builder);
}
//The driver,builder will be used by all the below 3 test functions.
/**
* Calling the Most Visited API -- TEST1
*/
public void test1(WebDriver driver,Actions builder){
WebElement most_visited_link = driver.findElement(By.id("mostVisited"));
Thread.sleep(2000);
Action mouseOvermost_visited_link = builder.moveToElement(most_visited_link).build();
mouseOvermost_visited_link.perform();
Thread.sleep(2000);
driver.findElement(By.id("mostVisited")).click();
Thread.sleep(1000);
WebElement most_Visited_button = driver.findElement(By.id("datePicked"));
Action mouse_most_VisitedOverDatePicker = builder.moveToElement(most_Visited_button).build();
mouse_most_VisitedOverDatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
test2(driver,builder);
}
/**
* Calling the Status Pie API -- TEST2
* #param builder
* #param driver
*/
public void test2(WebDriver driver,Actions builder){
WebElement status_pie_link = driver.findElement(By.id("statusPie"));
Thread.sleep(2000);
//Actions builder = new Actions(driver);
Action mouseOverStatusPie = builder.moveToElement(status_pie_link).build();
mouseOverStatusPie.perform();
Thread.sleep(1000);
driver.findElement(By.id("statusPie")).click();
Thread.sleep(1000);
WebElement status_pie_button = driver.findElement(By.id("datePicked"));
Action mouseOver_Status_pie_DatePicker = builder.moveToElement(status_pie_button).build();
mouseOver_Status_pie_DatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
test3(driver,builder);
}
/**
* Calling the Old Data API -- TEST3
*/
public void test2(WebDriver driver,Actions builder){
WebElement old_data_link = driver.findElement(By.id("oldData"));
Thread.sleep(2000);
// Actions builder = new Actions(driver);
Action mouseOverOldData = builder.moveToElement(old_data_link).build();
mouseOverOldData.perform();
Thread.sleep(2000);
driver.findElement(By.id("oldData")).click();
Thread.sleep(1000);
WebElement old_data_button = driver.findElement(By.id("datePicked"));
Action mouseOverDatePicker = builder.moveToElement(old_data_button).build();
mouseOverDatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
driver.quit();
}
}
The code executes as expected on the browser and closes the chrome window.
However, in the index report, I see log as :
3 methods, 2 skipped, 1 passed
Skipped methods :
mostVisitedfunction
statuspiefunction
Passed methods :
createConnection
Any idea where am I going wrong ?
Thanks in advance.
The method mostVisitedfunction should not have annotation because it is the helping method for yoyr test case. Instead create a new class, create a object of the same in the #test class and then call that method..
See the below example..
My test is
//MAximize the Screen
driver.manage().window().maximize();
//Go to Gmail Login Page
SignInPage SignInPage = WebUtils.GoToSignInPage(driver);
//Sign in to Login page -Send Username
SignInPage.SendkeysMethodForSignInPAge(driver, By.cssSelector("input[id='Email']") , "kishanpatelllll.8#gmail.com" );
//Click on Next
SignInPage.ClickToLogin(driver, By.cssSelector("input[id='next']"));
//Wait for password field to be visible
SignInPage.WaitForElementTobeVisible(driver, By.cssSelector("input[id='Passwd'][type='password']"));
So when i call the method SendkeysMethodForSignInPAge i wont write it in #Test.
See SendkeysMethodForSignInPAge method:
public class SignInPage {
public void SendkeysMethodForSignInPAge(WebDriver driver, By by, String s) {
WebUtils.Sendkeys(driver,by,s);
}
I created a new class and there i defined it.
This is basic flow.
Hope you can relate this.
Reply to me, if your are still stuck.
Happy Learning :-)
The error comes because if you have parameters in your #Test annotated method, then those need to come from #Parameters or #DataProvider. Else, if none of the annotation supplies the arguments, which is your case, then the error is thrown.
Apart from that what #Kishan has suggested in terms of structure of code is correct. You need to differentiate between your tests and common functions.
#Test
public void assertBackToLogin(WebDriver driver) throws InterruptedException {
LoginPage login = new LoginPage (driver);
login.assertLogin();
}
Is NOT working
Remove all the parameters and run
#Test
public void assertBackToLogin() throws InterruptedException {
LoginPage login = new LoginPage (driver);
login.assertLogin();
}
I have a requirement wherein
I need to invoke F12 developer tool in IE.
Navigate to profiler tab.
start profiler
I am using IE 9. In the below code, I am trying to navigate by entering ctrl5. It is not working.
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.HasInputDevices;
import org.openqa.selenium.interactions.Keyboard;
import org.testng.annotations.Test;
import org.openqa.selenium.remote.DesiredCapabilities;
public class InvokeIEbrowser {
#Test
public void IEdriver() {
System.setProperty("webdriver.ie.driver",
"D:\\2015\\softwares\\IEDriverServer_x64_2.48.0\\IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
capabilities.setCapability("ACCEPT_SSL_CERTS", true);
WebDriver driver = new InternetExplorerDriver();
/*
Keyboard keyboard = ((HasInputDevices) driver).getKeyboard();
keyboard.sendKeys(Keys.F12);
*/
/*
driver.get("http://mail.yahoo.com");
System.out.println(driver.getTitle());
*/
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//driver.FindElement(By.XPath("String")).SendKeys(Keys.NumberPad5);
//keyboard.sendKeys(Keys.CONTROL);
//getKeyboard().sendKeys(Keys.CONTROL, Keys.F5);
Actions actionObject = new Actions(driver);
actionObject.sendKeys(Keys.F12).perform();
//actionObject.sendKeys(Keys.CONTROL).sendKeys(Keys.NUMPAD5).keyUp(Keys.CONTROL).perform();
actionObject.sendKeys(Keys.CONTROL.NUMPAD5).perform();
System.out.println("done");
}
}
You could try using Keys.chord() (more about it here):
driver.FindElement(By.XPath("String")).SendKeys(Keys.chord(Keys.CONTROL, Keys.NUMPAD5 ));
or by using the Action class and the unicode representation:
Actions action = new Actions();
action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0035')).perform();
You can find more references about the unicode representation here.
Are you just trying to send the hotkey to the page? Try an extension of driver...
public static void sendCtrl5(this IWebDriver Driver)
{
Driver.FindElement(By.TagName("body")).Click(); // make window active
new Actions(Driver)
.SendKeys(Keys.Control + Keys.NumberPad5)
.Perform();
}
Use: driver.sendCtrl5();