How to check video loading in a URL? - java

I have a URL with a video embedded to it just like youtube URLs and i want to validate if the video loads and streams
The difficulty i am having is that i don't have the tagname , id or anything of the video element , so how can i check in such a case
Code using selenium:
public class URLCheck
{
public static void main(String args[]){
File file = new File("C:\\Users\\MB0000038\\Desktop\\chromedriver\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver=new ChromeDriver();
driver.get("https://www.youtube.com/watch?v=FtsrtcagbOQ");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// JavascriptExecutor js = (JavascriptExecutor) driver;
// WebElement video = driver.findElement(By.tagName("video"));
driver.quit();
}
}
This code works well but only open a chrome tab displaying the video
Thanks in advance

I have checked your video, there are two tags which you can play around to verify your video.
driver.get("https://www.youtube.com/watch?v=59rEMnKWoS4");
driver.manage().window().maximize();
WebElement pauseAndPlay = driver.findElement(By.xpath("//button[#class='ytp-play-button ytp-button']"));
//Get the attribute aria-lable of pauseAndPlay Element which would tells you current state of video(pause/play)
String videoState=pauseAndPlay.getAttribute("aria-label");
if(videoState.equalsIgnoreCase("Pause")){
System.out.println("Video is currently in play state");
Thread.sleep(3000);
//pausing my video and checking the current play time
pauseAndPlay.click();
Thread.sleep(2000);
WebElement currentTimeElement=driver.findElement(By.xpath("//span[#class='ytp-time-current']"));
String currentTime=currentTimeElement.getText();
if(currentTime!="0:00"){
System.out.println("my video is getting progressed and currently at:"+currentTime);
}else{
System.out.println("my video is not getting played");
}
}else if(videoState.equalsIgnoreCase("Play")){
System.out.println("Video is currently paused");
}

Related

Take a Screenshot with RemoteWebDriver

Is there a way to get selenium screenshots with headers ? I've tried the code below but the screenshot does not have a header.
I have a test case that requires clicking a link and making sure the action must bring to a new tab, so as evidence I have to attach capture there are two tabs.
public static void main (String args[]) throws IOException {
DesiredCapabilities dc = new DesiredCapabilities();
RemoteWebDriver driver;
URL url = new URL("http://localhost:4444/wd/hub");
dc.setCapability(CapabilityType.BROWSER_NAME, BrowserType.CHROME);
dc.setCapability(CapabilityType.PLATFORM, "MAC");
driver = new RemoteWebDriver(url, dc);
driver.manage().window().maximize();
driver.get("https://google.com");
new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.name("q")));
File getImage = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(getImage, new File("/Users/path/screenshot.jpg"));
driver.quit();
}
Current result
Expected result
No you can't, the screenshot functionality in Selenium takes an image of the rendered DOM. The browser chrome (i.e. the the UI components of the browser rendered by the OS the browser is running on) is not part of the DOM so Selenium is unaware of it.
The next question is why do you want the browser chrome in your image? If you are just trying to find out the displayed URL (as your question implies) you can use the command driver.getCurrentUrl(); instead.
As #Ardesco suggested, it is not possible to take screenshot.
However i think you can use java.awt.Robot class to capture the screen. It takes the screenshot of the current screen.
Here's an snapshot of code for capturing screenshot using java.awt,
public void getScreenshot(int timeToWait) throws Exception {
Rectangle rec = new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", setupFileNamePath());
}

Getting java.util.NoSuchElementException while trying to handle multiple browser windows using selenium webdriver with java

I am trying to handle multiple browser windows using selenium webdriver, but getting java.util.NoSuchElementException. A week ago this code was working fine but now getting issue in the code while trying to switch to third window.
The issue I am getting on line String Third_window = iterate.next();
Note: This code was working fine properly a week ago.
public class Firefox {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\singhais\\Documents\\Selenium Prerequisites\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get("https://www.hdfcbank.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// First window
System.out.println("GettingID for first Window");
Set<String> win = driver.getWindowHandles();
Iterator<String> iterate = win.iterator();
String first_window = iterate.next();
System.out.println(first_window);
driver.findElement(By.xpath("//*[#id='element2']/div[1]/div[3]/div[2]/a/img")).click();
// second window
System.out.println("GettingID for second Window");
win = driver.getWindowHandles();
iterate = win.iterator();
first_window = iterate.next();
System.out.println(first_window);
System.out.println(driver.getTitle());
String second_window = iterate.next();
System.out.println(second_window);
driver.switchTo().window(second_window);
Thread.sleep(10000);
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//*[#id='wrapp']/div[2]/div[3]/div[1]/div/div[2]/ul/li[1]/a")).click();
// ThirWindow
System.out.println("GettingID for third Window");
win = driver.getWindowHandles();
iterate = win.iterator();
first_window = iterate.next();
System.out.println(first_window);
second_window = iterate.next();
System.out.println(second_window);
String Third_window = iterate.next();
System.out.println(Third_window);
driver.switchTo().window(Third_window);
Thread.sleep(10000);
System.out.println(driver.getTitle());
Thread.sleep(3000);
driver.close();
driver.switchTo().window(second_window);
Thread.sleep(3000);
driver.close();
driver.switchTo().window(first_window);
driver.findElement(By.xpath("html/body/div[1]/div[1]/div[1]/div/div[2]/ul/li[2]/a")).click();
Thread.sleep(6000);
driver.close();
}
}
This code is not duplicate of the problem mentioned in given link below. In my issue I am getting NoSuchElementException while trying to navigate to last window.
Using Thread.sleep(3000); Your program works fine for me.I just wait 3s for getting next windows
System.out.println("GettingID for third Window");
Thread.sleep(3000);
win = driver.getWindowHandles();
iterate = win.iterator();
Please check and let me know

Selenium WebDriver not working fine on Amazon site

I am trying to write a Selenium test against Amazon site. I want to get "Sign in" element so that I can click on it.
url: www.amazon.es
Here is my Selenium Code:
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.amazon.es");
try
{
driver.findElement(By.id("nav-link-accountList")).click();
}
catch (Exception e)
{
System.out.println("Not Found");
}
Sometimes the code works correctly but sometimes it does not find the ID "nav-link-yourAccount". What is the problem? and how can I solve it?
Provide few seconds of wait, before click to this webelement so your driver may able to find the webelement.
For wait i am using Explicit wait method.
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("nav-link-accountList"))));
driver.findElement(By.id("nav-link-accountList")).click();
The element which you are trying to click with id as nav-link-yourAccount is not clickable. To proceed further you need to click either the link with text Hola. Identifícate or the link with text Mi cuenta using one of the following xpaths:
//a[#id='nav-link-yourAccount']/span[text()='Hola. Identifícate']
or
//a[#id="nav-link-yourAccount"]/span[contains(text(),'Mi cuenta')]
Instead using implicit wait try using explicit wait for the login element.
I've tried with explicit wait over 50 click and it did works.
Here is code you can use.
public class dump {
public static void main(String a[]){
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 15);
for(int i=0; i<=50; i++){
driver.get("https://www.amazon.es");
try{
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id='nav-link-accountList']")));
driver.findElement(By.xpath("//*[#id='nav-link-accountList']")).click();
System.out.println("clicked\t"+i);
}catch (Exception e){
e.printStackTrace();
System.out.println("Not Found");
}
}
}
}
Here is the proof of run:
All the best!!
Apply wait until element is appeared, so that it avoids NoSuchElementException and code is working without any error.
Below code is working fine:
driver.get("https://www.amazon.es");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement accontButton=driver.findElement(By.id("nav-link-accountList"));
WebDriverWait waitforelement=new WebDriverWait(driver,20);
waitforelement.until(ExpectedConditions.elementToBeClickable(accontButton));
try{
accontButton.click();
}
catch (Exception e){
System.out.println("Not Found");
}
Have you tried to find elements by xpath?
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.amazon.es");
try
{
driver.findElement(By.xpath("//*[#id='nav-link-accountList']")).click();
}catch (Exception e)
{
System.out.println("Not Found");
}

How to close the new windows in firefox that open after extracting elements from div using webdriver?

Webdriver launches multiple windows after performing click action. I have tried driver.close() but it close the webdriver and test fails.
WebDriver driver = new FirefoxDriver ();
driver.get("http://www.xyz.com/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement page = driver.findElement(By.className("coupon-rows"));
List <WebElement> coupontrigger = page.findElements(By.className("code"));
System.out.println("number of couponsTriggers on carousel = "+ "coupontrigger.size());
for (int j=0; j<=coupontrigger.size(); j++) {
js.executeScript("$('.ccode.coupon-trigger').eq("+j+").click()");
System.out.println(driver.getTitle());
driver.switchTo().defaultContent();
driver.get("http://www.xyz.com/");
page = driver.findElement(By.className("coupon-rows"));
coupontrigger = page.findElements(By.className("code"));
}
}
If I understood your requirement you want to close the other popups rather than the main window. In that case you can do below. Though I am not 100% sure of your requirement.
String mwh=driver.getWindowHandle(); // Get current window handle
Set<String> s=driver.getWindowHandles();
Iterator<String> ite=s.iterator();
String popupHandle = "";
while(ite.hasNext())
{
popupHandle = ite.next().toString();
if(!popupHandle.contains(mwh)) // If not the current window then shift focus and close them
{
driver.switchTo().window(popupHandle);
driver.close();
}
}
driver.switchTo().window(mwh); // finally move control to main window.
You can introduce a helper method which will do that task for you. You just need to find out what your current view is (WebDriver#getWindowHandle will give the one you have focus on) and then just close the rest of the windows.
private String closeAllpreviouslyOpenedWindows() {
String firstWindow = webDriver.getWindowHandle();
Set<String> windows = webDriver.getWindowHandles();
windows.remove(firstWindow);
for (String i : windows) {
webDriver.switchTo().window(i);
webDriver.close();
}
webDriver.switchTo().window(firstWindow);
return firstWindow;
}

Selenium takes lots of time to get dynamic page of given URL

I am doing a Project in Java.
In this project I have to work with DOM.
For that I first load a dynamic page of any given URL, by using Selenium.
Then I parse them using Jsoup.
I want to get the dynamic page source code of given URL
Code snapshot:
public static void main(String[] args) throws IOException {
// Selenium
WebDriver driver = new FirefoxDriver();
driver.get("ANY URL HERE");
String html_content = driver.getPageSource();
driver.close();
// Jsoup makes DOM here by parsing HTML content
Document doc = Jsoup.parse(html_content);
// OPERATIONS USING DOM TREE
}
But the problem is, Selenium takes around 95% of the whole processing time, that is undesirable.
Selenium first opens Firefox, then loads the given page, then gets the dynamic page source code.
Can you tell me how I can reduce the time taken by Selenium, by replacing this tool with another efficient tool. Any other advice would also be welcome.
Edit NO. 1
There is some code given on this link.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "some UA string");
WebDriver driver = new FirefoxDriver(profile);
But what is second line here, I didn't understand. As Documentation is also very poor of selenium.
Edit No. 2
System.out.println("Fetching %s..." + url1);
System.out.println("Fetching %s..." + url2);
WebDriver driver = new FirefoxDriver(createFirefoxProfile());
driver.get("url1");
String hml1 = driver.getPageSource();
driver.get("url2");
String hml2 = driver.getPageSource();
driver.close();
Document doc1 = Jsoup.parse(hml1);
Document doc2 = Jsoup.parse(hml2);
Try this:
public static void main(String[] args) throws IOException {
// Selenium
WebDriver driver = new FirefoxDriver(createFirefoxProfile());
driver.get("ANY URL HERE");
String html_content = driver.getPageSource();
driver.close();
// Jsoup makes DOM here by parsing HTML content
// OPERATIONS USING DOM TREE
}
private static FirefoxProfile createFirefoxProfile() {
File profileDir = new File("/tmp/firefox-profile-dir");
if (profileDir.exists())
return new FirefoxProfile(profileDir);
FirefoxProfile firefoxProfile = new FirefoxProfile();
File dir = firefoxProfile.layoutOnDisk();
try {
profileDir.mkdirs();
FileUtils.copyDirectory(dir, profileDir);
} catch (IOException e) {
e.printStackTrace();
}
return firefoxProfile;
}
The createFireFoxProfile() method creates a profile if one doesn't exist. It uses if a profile already exists. So selenium doesn't need to create the profile-dir structure each and every time.
if you are sure, confident about your code, you can go with phantomjs. it is a headless browser and will get your results with quick hits. FF will take time to execute.

Categories

Resources