how properly check page title? - java

I use Selenium WebDriver in Eclipse.
I write method to check if title is displayed correctly. Here is the code:
class Check {
String text_to_found;
String reason;
Check (String t, String r) {
text_to_found=t;
reason=r;
}
public void check_title() {
try {
Assert.assertTrue("Title " + text_to_found + " not found", text_to_found.equals(reason));
} catch (AssertionError e) {
System.err.println("title not found: " + e.getMessage());
}
}
I call it with such command:
Check title1 = new Check ("Title", driver.getTitle());
title1.check_title();
First time it works correct. But second (and so on) times, if I call this method (for new opened windows) it says that title is not found, but I know that it is correct. Advise, what is wrong with code?

I just used your code to check the title of google.com. In your code if the title does not match -
Check title1 = new Check ("G3oogle", driver.getTitle());
title1.check_title();
We get the result - title not found: Title G3oogle not found
But if it matches as below -
Check title1 = new Check ("Google", driver.getTitle());
title1.check_title();
You are not printing anything on the console. So if you want print anything to the console if title matches then you can modify your code -
public void check_title() {
if(text_to_found.equals(reason)){
System.out.println("title found: Title "+text_to_found+" found");
}
else{
System.out.println("title not found: Title "+text_to_found+" not found");
}
}

Related

How do I Check search keyword in the URL

I am a beginner in Selenium. I wanted to know how I can verify the URL against the keyword I entered in the search bar.
The search page url is https://catalog-mytest.com/search?
When I entered redcar in the search bar and hit enter, the url becomes https://catalog-mytest.com/search?keywords=redcar
Could you guide me on how to write a piece of code that would verify the URL with the keywords? thank you.
There can be two approaches-
Approach-1:
String url = Driver.getCurrentUrl();
boolean passed = url.contains("your keyword here");
if (passed) {
System.out.println("Test Passed");
} else {
System.out.println("Test Failed");
Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}
This is the simplest way of doing this.
Approach-2:
String keyword = Driver.getCurrentUrl().split("?")[1].split("=")[1];
boolean passed = keyword.equals("your keyword here");
if (passed) {
System.out.println("Test Passed");
} else {
System.out.println("Test Failed");
Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}
This approach can be error prone, if the URL does not always contain
?, = in it then the test can fail with
ArrayIndexOutOfBoundsException

Selenium Java returns incorrect results for element.isDisplayed

I am running tests using Java, Selenium & TestNG.
(selenium-server-standalone.3.8.3, Java 8 Update 151)
I am using Firefox Quantum 61.0.2 (64-bit) as browser.
I have a problem where an element I need to click on is dissappearing, and I want to log an error when this occurs.
Unfortunately, element.isDisplayed returned true when to element is clearly no there.
What makes diagnosing this problem difficult is that clicking the 'invisible' element actually works, but still leads to unpredictable results.
How can I get the correct answer?
This is an example of code used:
public static boolean isElementDisplayed(String className, String textToFind, String htmlElement,
WebDriver driver) {
// String className = "map-popup-button";
// String textToFind = "icon-structure-tree";
// String htmlElement = "button";
List<WebElement> elements = Common.findElementsUsingHtmlXpathClass(driver, htmlElement, className);
Common.myPrint(thisClass + " elements count: " + elements.size());
String text = "";
String attr = "";
for (WebElement element : elements) {
// select an element
if(!Common.retryingIsElementDisplayed(element)) {
Common.scrollIntoView(element, driver);
}
if (Common.retryingIsElementDisplayed(element)) {
text = element.getAttribute("innerHTML");
if (text != "") {
text = text.trim();
if (text.contains(textToFind)) {
Common.myPrint(thisClass + " innerHTML: " + text);
return true;
}
}
attr = Common.getAllAttributes(element, driver);
if (attr.contains(textToFind)) {
Common.myPrint(thisClass + " attr: " + text);
return true;
}
}
}
return false;
}
and that retryingIsElementDisplayed function:
public static boolean retryingIsElementDisplayed(WebElement element) {
// myPrint(thisClass + " retryingIsElementDisplayed...");
boolean result = false;
int attempts = 0;
while (attempts < 2) {
try {
result = element.isDisplayed();
break;
} catch (StaleElementReferenceException e) {
int errorCode = 1533564891;
Common.myPrint(thisClass + " error code: " + errorCode +" Exception: " + e.getMessage());
Common.myPrint(thisClass + " *** INFO ONLY *** ");
}
attempts++;
}
return result;
}
Tests have shown that this problem occurs after using javascriptExecutor.executeScript("arguments[0].scrollIntoView(true);", element); on a different element. This is scrolling my logo up out of view. When I manually scroll back down, the element is no longer visible (but still - presumably - present in the DOM)
This is HTML of the element I am looking for:
<svg version="1.1" id="Vector_Smart_Object_xA0_Image_1_" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 300 50" style="enable-background:new 0 0 300 50;" xml:space="preserve">
.st0{fill:#FFF;}
</style>
<g>
<polygon class="st0" points="119.2,12.4 126.3,12.4 126.3,31.3 138.4,31.3 138.4,37.5 119.2,37.5 "></polygon>
<polygon class="st0" points="140.3,12.4 147.3,12.4 147.3,31.3 159.4,31.3 159.4,37.5 140.3,37.5 "></polygon>
<polygon class="st0" points="202.1,12.4 197.1,21.5 192,12.4 184,12.4 193.6,28.3 193.6,37.4 200.7,37.4 200.7,28.3 210.2,12.4 "></polygon>
<path class="st0" d="M172.7,11.7c-7.4,0-13.5,6-13.5,13.3s6.2,13.3,13.5,13.3c7.4,0,13.3-6,13.3-13.3s-6.2-13.3-13.5-13.3 M172.6,31.6c-3.5,0-6.3-3-6.3-6.7s2.8-6.7,6.3-6.7c3.5,0,6.3,3,6.3,6.7S176.1,31.6,172.6,31.6"></path>
<path class="st0" d="M107.2,12.2h-6.7L89.8,37.5h7.3l2-4.6l9.4,0.1l1.8,4.5h7.4L107.2,12.2z M101.3,27.1l2.6-6.5l2.6,6.5H101.3z"></path>
</g>
</svg>
You are making this way harder than it needs to be. You are passing Strings used to locate elements around instead of using the Selenium-supplied By locator class.
A simple example given the HTML element you want to find.
<svg version="1.1" id="Vector_Smart_Object_xA0_Image_1_" ...>
We can find this element using a simple By.id() locator, e.g.
By svgElementLocator = By.id("Vector_Smart_Object_xA0_Image_1_");
Now you can pass this into a function that checks to see if it's displayed or not.
public static boolean isElementDisplayed(WebDriver driver, By locator) {
try {
return driver.findElement(locator).isDisplayed();
break;
} catch {
return false;
}
}
Because you are no longer passing around a WebElement, you don't have to worry about StaleElementExceptions, etc. and your code is much simpler. You can call this like
bool result = isElementDisplayed(driver, svgElementLocator);
Just to be clear, .isDisplayed() has nothing to do with whether the element is on the screen or not... it has to do with whether it's not visible, e.g. display: none, etc. See the docs.
Is this element displayed or not? This method avoids the problem of having to parse an element's "style" attribute.
You can store the same web element in a list.
Demonstration code would look like this :
List<WebElement> errorMsg = driver.findElements(By.xpath("xpath for error msg"));
if(errorMsg.size()>0) {
//do something when error occurs
}
else {
//your script knows , that there is no error msg.
}

Button.isEnabled() returns true even though the button is disabled by default [duplicate]

This question already has answers here:
Button enabled or disabled : How does webdriver decide?
(2 answers)
Closed 5 years ago.
While testing I got a road block where I have a button in a WebPage which is disabled by default. I am using Selenium WebDriver to test if the button is disabled by default the boolean is always returning true.
Boolean buttonStatus = (button XPath).isEnabled
It will be great if someone can help me
HTML Information:
<div class="commandbutton commandbutton--theme-disabled commandbutton--recommended">
<button class="commandbutton-button commandbutton-button--disabled" type="button" tabindex="-1">
From isEnabled docs
This will generally return true for everything but disabled input
elements.
But it will work on buttons as well. However, isEnabled() checks for the disabled attribute. If the button is disabled by JavaScript or any other means isEnabled() won't detect it.
My guess is the button has other classes when it is enabled or disabled. For example, when enabled it probably won't have commandbutton-button--disabled class. You can check for it
WebElement button = driver.findElement(By.xpath("button XPath"));
String classes = button.getAttribute("class");
boolean isDisabled = classes.contains("commandbutton-button--disabled");
I had the same problem. But my elements on the page were very strange. Some of them selenium could click although they were not clickable, some of them selenium couldn't click, but could send keys to them. After a few hours of thinking, I have wrote universal method, that checks if elements is enabled or not.
After talking with programmer, I have known, that they use on this page some special Select, and it looks like Div with Input in it. And he says, that I can check it disabling by checking attribute Class of Div. If there is 'select2-container-disabled' then this Input is disabled.
And I change my method. Now it looks like that:
public boolean isNotClickable(WebElement... elements) {
List<WebElement> elementsChecked = new ArrayList<>();
List<WebElement> elementsToCheckByClass = new ArrayList<>();
List<WebElement> elementsToCheckByClick = new ArrayList<>();
List<WebElement> elementsToCheckBySendKeys = new ArrayList<>();
for (WebElement checkedElement : elements) {
log.info("Checking, that element [" + getLocator(checkedElement) + "] is not clickable by isEnabled()");
if (checkedElement.isEnabled()) {
elementsToCheckByClass.add(checkedElement);
} else {
elementsChecked.add(checkedElement);
}
}
if (!elementsToCheckByClass.isEmpty()) {
for (WebElement checkedByClassElement : elementsToCheckByClass) {
log.info("Checking, that element [" + getLocator(checkedByClassElement) + "] is not clickable by class");
String classOfElement = checkedByClassElement.getAttribute("class");
List<String> classes = new ArrayList<>(Arrays.asList(classOfElement.split(" ")));
if (!classes.contains("select2-container-disabled")) {
elementsToCheckByClick.add(checkedByClassElement);
} else {
elementsChecked.add(checkedByClassElement);
}
}
}
if (!elementsToCheckByClick.isEmpty()) {
WebDriverWait wait = new WebDriverWait(driverUtils.getDriver(), 1);
for (WebElement checkedByClickElement : elementsToCheckByClick) {
log.info("Checking, that element [" + getLocator(checkedByClickElement) + "] is not clickable by clicking it");
try {
wait.until(elementToBeClickable(checkedByClickElement));
elementsToCheckBySendKeys.add(checkedByClickElement);
} catch (Exception e) {
elementsChecked.add(checkedByClickElement);
}
}
}
if (!elementsToCheckBySendKeys.isEmpty()) {
for (WebElement checkedBySendKeysElement : elementsToCheckBySendKeys) {
log.info("Checking, that element [" + getLocator(checkedBySendKeysElement) + "] is not clickable by sending keys");
try {
checkedBySendKeysElement.sendKeys("checking");
return false;
} catch (Exception e) {
elementsChecked.add(checkedBySendKeysElement);
}
}
}
return elementsChecked.size() == elements.length;
}
isEnabled can only tell you the button works fine, you need to check the class attribute to check is the button is enabled.

HtmlUnit won't change TextArea's text

I have written a code to connect to this webpage: compilerjava.net
1) I found the text-area field within that page which accepts the code to compile.
2) I have found the button that compiles the code.
3) I have found the text-area which returns the result of the code.
The issue is, when I call textarea.setText( "something"), it (I think) doesn't actually change the code in the webpage. So when I click on the compile button, it compiles the default code within that page and returns the output of that default code.
I have tried to set focus to textarea, you can see all of those down below.
I called;
1) textArea.focus();
2) textArea.click();
3) I tried using textArea.setAttribute( "name", "code");
I have searched the internet and found various stackoverflow questions close to this problem, neither of them solved my issue and it just seems to work for everyone when they say textArea.setText().
Another interesting fact I should share with you is,
If I call textArea.setText( "...") and then I say;
HtmlTextArea textArea1 = form.getTextAreaByName( "code");
If I call textArea1.getText(), the value of this text will be "...". This should imply that I have actually managed to change the value of the text-area, but when I compile, it compiles the default text in the text-area and not the text that I have set it to.
Any help with this?
P.S: The reason why I put the result of the compilation on a while loop is related to network connection issues. If you try to run this code it might not work on your first try. Also note that the run-time is around 15 seconds, because it gives thousands of warnings which I blocked to print to console.
P.S2: I also looked at this page and none of these worked;
http://www.programcreek.com/java-api-examples/index.php?api=com.gargoylesoftware.htmlunit.html.HtmlTextArea
public class Test {
public static void main(String[] args) {
try {
// Prevents the program to print thousands of warning codes.
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
// Initializes the web client and yet again stops some warning codes.
WebClient webClient = new WebClient( BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnFailingStatusCode( false);
webClient.getOptions().setThrowExceptionOnScriptError( false);
webClient.getOptions().setJavaScriptEnabled( true);
webClient.getOptions().setCssEnabled( true);
// Gets the html page, which is the online compiler I'm using.
HtmlPage page = webClient.getPage("https://www.compilejava.net/");
// Succesfully finds the form which has the required buttons etc.
List<HtmlForm> forms = page.getForms();
HtmlForm form = forms.get( 0);
// Finds the textarea which will hold the code.
HtmlTextArea textArea = form.getTextAreaByName( "code");
// Finds the textarea which will hold the result of the compilation.
HtmlTextArea resultArea = page.getHtmlElementById( "execsout");
// Finds the compile button.
HtmlButtonInput button = form.getInputByName( "compile");
textArea.click();
textArea.focus();
// Simple code to run.
textArea.setDefaultValue( "public class HelloWorld\n" +
"{\n" +
" // arguments are passed using the text field below this editor\n" +
" public static void main(String[] args)\n" +
" {\n" +
" System.out.print( \"Hello\");\n" +
" }\n" +
"}");
System.out.println( textArea.getText());
// Compiles.
button.click();
// Result of the compilation.
String str = resultArea.getText();
while ( resultArea.getText() == null || resultArea.getText().substring(0, 3).equals( "exe")) {
System.out.print( resultArea.getText());
}
System.out.println();
System.out.println( resultArea.getText());
} catch ( Exception e) {
e.printStackTrace();
}
}
}
a little patience helps here
// Result of the compilation.
while (resultArea.getText() == null || resultArea.getText().startsWith("exe")) {
System.out.println(resultArea.getText());
Thread.sleep(500);
}
System.out.println();
System.out.println(resultArea.getText());

How can I simplify this selenium / java code to get it working?

Can somebody help me with the following Java code used in a selenium webdriver test? I know there are probably better ways to do it but the previous person who worked on it before I took over was learning on the job.
Basically it gets to a page and checks for different elements if it finds them it enters some data into field.
The problem is this code is run against different sites and now there is a problem where on one of the pages the text To date and to_date are both on the page so the test fails because it finds an element endDateParam but no the element to_date.
Can anybody help me get around this? I need it so if it finds the text to_date on the page it will use the to_date param, if it finds the text To date it will use the endDateParam and if it finds the text To date AND to_date it will use which ever param it finds.
I tried adding a try catch which does nothing when caught but it still fails.
if (PWSHelper.verifyTextPresent("To date", driver))
{
try {
WebElement toDate = driver.findElement(By.name("endDateParam"));
toDate.sendKeys(boHelper.nextWeek());
} catch (NoSuchElementException ex)
{
System.out.println("endDateParam Not Found");
System.out.println();
}
}
if (PWSHelper.verifyTextPresent("to_date", driver))
{
try {
WebElement toDate = driver.findElement(By.name("to_date"));
toDate.sendKeys(boHelper.nextWeek());
} catch (NoSuchElementException ex)
{
System.out.println("to_date Not Found");
System.out.println();
}
}
How about a function that can be called with your different parameters:
private void doSomething(String textToFind, String target)
if (PWSHelper.verifyTextPresent(textToFind, driver))
{
try {
WebElement toDate = driver.findElement(By.name(target));
toDate.sendKeys(boHelper.nextWeek());
} catch (NoSuchElementException ex)
{
System.out.println(textToFind + " Not Found");
System.out.println();
}
}

Categories

Resources