I've written a code using Selenium WD and JUnit that should check if proper page is loaded and the table of this page is not null
Besides assertion, to make sure that proper page is loaded (checking if URL contains specified text), I've put "if-else" statement in "waitUntilPageLoaded" method.
import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class GuruSearch
{
#Test
static void checkDemoLogin()
{
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pansa\\Documents\\Webdrivers\\geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 10);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(FirefoxDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The "if-else" statement in "waitUntilPageLoaded" method returns "OK", but TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"))
throws AssertionError, although the text appears in the page.
Why there is AssertionError thrown?
As you are using the JUnit annotations, the annotated method shouldn't be static. I have modified your code a bit, try the below:
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.TestCase;
public class GuruSearch
{
#Test
public void checkDemoLogin()
{
System.setProperty("webdriver.chrome.driver", "C:\\NotBackedUp\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 30);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(WebDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The above code is printing 'OK' and Assert condition also passing. And I think, it doesn't matter if we give upper/lower case in the contains. It will match both the cases.
I don't have Firefox in my system so I have checked with Chrome, you change the browser and try... I hope it helps...
Related
My Xpath is correct & no iFrame and I can locate element in Chrome console but my program still fails. I have used explicit wait also.
Website: https://qrgo.page.link/8YEcD I am trying to locate the male gender radio button.
I can locate the element in the same chromedriver console but still it shows no element found exception.
Code:-
package automation;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class residence {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", ".\\lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://serviceonline.bihar.gov.in/resources/homePage/10/loginEnglish.htm");
driver.findElement(By.xpath("//label[contains(text(),'General')]")).click();
driver.findElement(By.xpath(("//p[contains(text(),'Residential')]"))).click();
driver.findElement(By.xpath(("//div[#id='collapseOneOne']/div/p/a"))).click();
/* Write Gender accordingly.Default is Male(M).(F) and (T)*/
char gender='M';
WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='17290_1']")));
if(gender=='M')
{
driver.findElement(By.xpath("//input[#id='17290_1']")).click();
}
else if(gender=='F')
{
driver.findElement(By.xpath("//input[#id='17290_2']")).click();
}
else
{
driver.findElement(By.xpath("//input[#id='17290_3']")).click();
}
}
}
Here is a screenshot of the chrome window in which the testcase run:
Here also u can see that element is visible
Error message image
When click on the link, it is opening a new tab, you need to switch to new tab before accessing the element.
package automation;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class residence {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", ".\\lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://serviceonline.bihar.gov.in/resources/homePage/10/loginEnglish.htm");
// Store the current window handle
String parent_handle = driver.getWindowHandle();
driver.findElement(By.xpath("//label[contains(text(),'General')]")).click();
driver.findElement(By.xpath(("//p[contains(text(),'Residential')]"))).click();
driver.findElement(By.xpath(("//div[#id='collapseOneOne']/div/p/a"))).click();
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
if(!parent_handle.equals(winHandle))
{
driver.switchTo().window(winHandle);
}
}
/* Write Gender accordingly.Default is Male(M).(F) and (T)*/
char gender='M';
WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[#for='17290_1']")));
if(gender=='M')
{
driver.findElement(By.xpath("//label[#for='17290_1']")).click();
}
else if(gender=='F')
{
driver.findElement(By.xpath("//label[#for='17290_2']")).click();
}
else
{
driver.findElement(By.xpath("//label[#for='17290_3']")).click();
}
}
}
I am a beginner in selenium, I am using java for thatU nill yesterday this code was working well, it showed me same exception for the button named "show". I searched for it and solved it. But again today its showing for clicking on list please help me. Also can I use wait named as domPropertyToBe
My java code:
import java.time.Duration;
import java.util.List;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
public class erp {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Tools\\Selenium\\Chromedriver96\\chromedriver_win32 (1)\\chromedriver.exe");
WebDriver dChromedriver=new ChromeDriver();
dChromedriver.get("https://erp.mitwpu.edu.in/");
dChromedriver.manage().window().maximize();
WebElement txtPassword=dChromedriver.findElement(By.id("txtPassword")) ;
WebElement txtUserId=dChromedriver.findElement(By.id("txtUserId")) ;
txtUserId.sendKeys("S1032200787");
txtPassword.sendKeys("FynS#3XbZH6ZMWH");
//
WebDriverWait w =new WebDriverWait(dChromedriver, Duration.ofSeconds(30));
w.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#id='ReCaptchContainer']")));
dChromedriver.findElement(By.xpath("//div[#id='ReCaptchContainer']")).click();
// Thread.sleep(3000);
w.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("label#lblMessage")));
WebElement success_lablElement=dChromedriver.findElement(By.cssSelector("label#lblMessage"));
Assert.assertEquals(success_lablElement.getText(),"Success" );
dChromedriver.findElement(By.id("btnLogin")).click();
WebElement resultWebElement=dChromedriver.findElement(By.xpath("//nav[#class=\"mt-2\"]/ul/li[12]/a[#href=\"Examination/Report/StudentGradeCardDetail.aspx?MENU_CODE=Web_Result\"]"));
resultWebElement.click();
w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("FrameContent")));
// w.until(ExpectedConditions.elementToBeClickable(By.id("drpSem_Arrow")));
dChromedriver.findElement(By.id("drpSem_Arrow")).click();
w.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.tagName("li")));
List<WebElement> listElement=dChromedriver.findElements(By.tagName("li"));
w.until(ExpectedConditions.elementToBeClickable(By.id("btnshow")));
WebElement show_buttonElement=dChromedriver.findElement(By.id("btnshow"));
// dChromedriver.findElement(By.cssSelector("a[onclick=\"$find('ReportViewer1').exportReport('PDF');\"]"));
for (WebElement list : listElement) {
if (list.getText().equals("SY BTech - CSE / TRIMESTER-V / 2020-21 / Middle")) {
list.click(); // This is the line I get error
show_buttonElement.click();
}
}
}
// public static void myfunction() {
// try {
// Robot robot = new Robot();
// Thread mthread = new Thread(mlauncher);
// mthread.start();
//
// robot.keyPress(KeyEvent.VK_ENTER);
// robot.keyRelease(KeyEvent.VK_ENTER);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
Goal: I have a class called "InvokeChromeTest" I'm extending to another class called "Base" to access chromedriver and data.properties. When running my code, I get the error:
Error:(22, 3) java: missing return statement
I am unsure how to fix this. Here is my sample code as follows. Please let me know what I can do to fix.
src/test/java/loginPage/InvokeChromeTest
package loginPage;
import credentials.ProfileCredentials;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import resources.Base;
public class InvokeChromeTest extends Base {
#Test
public WebDriver initializeDriver() {
driver = initializeDriver();
driver.get(dataProperties.getProperty("url"));
ProfileCredentials p = new ProfileCredentials(driver);
p.getAuthorize().click();
p.getApiKey().sendKeys("testKey");
p.getAuthCred().click();
p.getCloseAuth().click();
}
#AfterTest
public void teardown() {
driver.close();
}
}
src/main/java/resources/Base
package resources;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Base {
public WebDriver driver;
protected Properties dataProperties;
public WebDriver initializeDriver() {
// Create global property file
dataProperties = new Properties();
InputStream dataPropertiesInputStream = null;
try{
dataPropertiesInputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
dataProperties.load(dataPropertiesInputStream);
} catch (IOException e) {
e.printStackTrace();
}
String browserName = dataProperties.getProperty("browser");
System.out.println(browserName);
if (browserName.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
src/main/java/credentials/ProfileCredentials
package credentials;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class ProfileCredentials {
WebDriver driver;
public ProfileCredentials(WebDriver driver) {
this.driver = driver;
}
private By authorize = By.xpath("//button[#class='btn authorize unlocked']");
private By apikey = By.xpath("//div[#class='wrapper']//section//input");
private By authorizecred = By.xpath("//button[#class='btn modal-btn auth authorize button']");
private By closeauth = By.xpath("//button[#class='btn modal-btn auth btn-done button']");
public WebElement getAuthorize() {
return driver.findElement(authorize);
}
public WebElement getApiKey() {
return driver.findElement(apikey);
}
public WebElement getAuthCred() {
return driver.findElement(authorizecred);
}
public WebElement getCloseAuth() {
return driver.findElement(closeauth);
}
}
I figured out the problem. "Base" and "InvokeChromeTest" had the same method name. This is why it was recursive.
I am trying to get data from a webpage (http://steamcommunity.com/id/Winning117/games/?tab=all) using a specific tag but I keep getting null. My desired result is to get the "hours played" for a specific game - Cluckles' Adventure in this case.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class TestScrape {
public static void main(String[] args) throws Exception {
String url = "http://steamcommunity.com/id/Winning117/games/?tab=all";
Document document = Jsoup.connect(url).get();
Element playTime = document.select("div#game_605250").first();
System.out.println(playTime);
}
}
Edit: How can I tell if a webpage is using JavaScript and is therefore unable to be parsed by Jsoup?
To execute javascript in java code there is Selenium :
Selenium-WebDriver makes direct calls to the browser using each
browser’s native support for automation.
To include it with maven use this dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.4.0</version>
</dependency>
Next I give you code of simple JUnit test that creates instance of WebDriver and goes to given url and executes simple script to get rgGames .
File chromedriver you have to download at https://sites.google.com/a/chromium.org/chromedriver/downloads.
package SeleniumProject.selenium;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.TestCase;
#RunWith(JUnit4.class)
public class ChromeTest extends TestCase {
private static ChromeDriverService service;
private WebDriver driver;
#BeforeClass
public static void createAndStartService() {
service = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("D:\\Downloads\\chromedriver_win32\\chromedriver.exe"))
.withVerbose(false).usingAnyFreePort().build();
try {
service.start();
} catch (IOException e) {
System.out.println("service didn't start");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#AfterClass
public static void createAndStopService() {
service.stop();
}
#Before
public void createDriver() {
ChromeOptions chromeOptions = new ChromeOptions();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
driver = new RemoteWebDriver(service.getUrl(), capabilities);
}
#After
public void quitDriver() {
driver.quit();
}
#Test
public void testJS() {
JavascriptExecutor js = (JavascriptExecutor) driver;
// Load a new web page in the current browser window.
driver.get("http://steamcommunity.com/id/Winning117/games/?tab=all");
// Executes JavaScript in the context of the currently selected frame or
// window.
ArrayList<Map> list = (ArrayList<Map>) js.executeScript("return rgGames;");
// Map represent properties for one game
for (Map map : list) {
for (Object key : map.keySet()) {
// take each key to find key "name" and compare its vale to
// Cluckles' Adventure
if (key instanceof String && key.equals("name") && map.get(key).equals("Cluckles' Adventure")) {
// print all properties for game Cluckles' Adventure
map.forEach((key1, value) -> {
System.out.println(key1 + " : " + value);
});
}
}
}
}
}
As you can see selenium loads page at
driver.get("http://steamcommunity.com/id/Winning117/games/?tab=all");
And to get data of all games by Winning117 it returns rgGames variable:
ArrayList<Map> list = (ArrayList<Map>) js.executeScript("return rgGames;");
The page you want to scrape is load by js,and there is not any #game_605250 element that jsoup get.All datas are write in page by using js.
But when I print document to a file ,I see some data like this:
<script language="javascript">
var rgGames = [{"appid":224260,"name":"No More Room in Hell","logo":"http:\/\/cdn.steamstatic.com.8686c.com\/steamcommunity\/public\/images\/apps\/224260\/670e9aba35dc53a6eb2bc686d302d357a4939489.jpg","friendlyURL":224260,"availStatLinks":{"achievements":true,"global_achievements":true,"stats":false,"leaderboards":false,"global_leaderboards":false},"hours_forever":"515","last_played":1492042097},{"appid":241540,"name":"State of Decay","logo":"http:\/\/....
then,you can extract 'rgGames' by some StringTools and format it to json obj.
It't not a clerver method,but it worked
try this :
public class TestScrape {
public static void main(String[] args) throws Exception {
String url = "http://steamcommunity.com/id/Winning117/games/?tab=all";
Document document = Jsoup.connect(url).get();
Element playTime = document.select("div#game_605250");
Elements val = playTime.select(".hours_played");
System.out.println(val.text());
}
}
I downloaded the code below and used it for some tests and u=it ran yesterday but since today the code stopped working. My tests are failing now which was not happening before. It throws up an error saying org.openqa.selenium.ElementNotVisibleException: element is not currently visible so cannot interact with element.
package org.openqa.selenium.example;
//import org.openqa.selenium.browserlaunchers.locators.GoogleChromeLocator;
//import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
//import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.chrome.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.Select;
//import org.openqa.selenium.net.UrlChecker;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class KongaUrlTest
{
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception
{
driver = new FirefoxDriver();
baseUrl = "http://www.konga.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testFirefoxWebdriver() throws Exception
{
driver.get(baseUrl);
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();
try
{
assertEquals("Phones & Tablets | Konga Nigeria", driver.getTitle());
System.out.println(driver.getTitle());
}
catch (Error e)
{
verificationErrors.append(e.toString());
}
}
#After
public void tearDown() throws Exception
{
System.out.println(driver.getCurrentUrl());
driver.quit();
}
}
There's a blocking dialog being displayed. It's probably displayed each time Selenium opens a new browser and navigates to that site. Close that dialog first:
driver.get(baseUrl);
try
{
driver.findElement(By.cssSelector(".fancybox-close")).click();
}
catch { }
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();