Posted on Leave a comment

Selenium Basic Authentication via URL

Introduction

There are instances where you would work with applications that have their security behind the basic HTTP Authentication, also known as the Basic Authentication. Before you can be granted access to these sites or apps, you will be required to run some credentials through the website where you are requesting a page. If you cannot run those credentials through the website, you will have to deal with a pop up at a system level that prompts users for a username and password. This situation renders your Selenium helpless.

In the initial versions before Selenium 2, it is possible to execute it through the injection of credentials into a custom header. However, due to some advancements, another way to go about this is the Browsermob proxy, which is quite complex. We will discuss a simpler way here.

It is essential to recognize that the basic authentication feature is still working correctly with geckodriver v0.18.0, Mozilla Firefox 53.0, Selenium 3.4.0, Google Chrome 60.x, and chromedriver v2.31.488763, through Selenium Java bindings. This is a tested and working code that successfully opens using a valid set of credentials to access the URL.

For Mozilla Firefox,

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class BasicAuthentication_FF
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver =  new FirefoxDriver();
        driver.navigate().to("http://admin:admin@the-internet.herokuapp.com/basic_auth");
    }
}

For Chrome,

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class BasicAuthentication_Chrome
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        options.addArguments("--disable-extensions");
        WebDriver driver =  new ChromeDriver(options);
        driver.navigate().to("http://admin:admin@the-internet.herokuapp.com/basic_auth");
    }
}

You should note that the basic authentication via URL is blocked only for sub-resources, thus creating the possibility of using it on the domain as follows:

driver.get("http://admin:admin@localhost:8080");
driver.get("http://localhost:8080/project");

It is also possible to create a small extension to automatically set the credentials when they are requested as follows:

options = webdriver.ChromeOptions()
options.add_extension(r'C:\dev\credentials.zip')

Posted on Leave a comment

How to Open Chrome profile through Python

Ever since the announcement from Google that it will be shipping Headless Chrome, a lot of people have turned to using python to drive Chrome. This may be attributed to the fact that headless browsers have no Graphical User interface (GUI), as well as being navigated using a command line interface or a program. Many, however turn to driving Chrome using python due to the fact that it’s much more fun.

To drive Chrome through Python, however, a lot of people face obstacles like opening a Chrome profile through Python which is required before any other action can be taken. Here, we will discuss the steps to follow on how to open a Chrome profile through Python.

Step by Step Guide to Open Chrome Profile through Python

  • Launch your chrome browser, then click open chrome settings where chrome://settings/ is displayed
  • Go to People section, select Manage Other people
  • Click on Add Person
  • Input your name and pick one of numerous icons displayed
  • You have to Check the ‘Create a desktop shortcut for this user’ item
  • Click the Add button.
  • Your new profile is successfully created

This is a sample of how your newly opened profile should look like:

  • You will find a desktop icon tagged SeLeNiUm – Chrome
  • Through the properties of the SeLeNiUm – Chrome, get the name of the profile directory. e.g. –profile-directory=”Profile 2″. An example of this is shown below:
  • Obtain the absolute path of the profile-directory in your computer using the following:
C:\\Users\\Otaku_Wiz\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 2
  • Then pass the value of profile-directory through an instance of Options with add_argument() method along with key user-data-dir as shown below:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("user-data-dir=C:\\Users\\AtechM_03\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 2")
driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe', chrome_options=options)
driver.get("https://www.google.co.in")
  • Launch your Test and you will notice your Chrome is initiated with the Chrome profile as Selenium
Posted on Leave a comment

The Difference between JavaScript Click () and WebDriver Click ()

There are several situations where users run into problems concerning the inability to click an element through the selenium WebDriver “click” command but can easily execute it with a JavaScript click. An example of this scenario in both Python and WebDriver JavaScript is provided below:

In Python,

element = driver.find_element_by_id("myid")
driver.execute_script("arguments[0].click();", element)
While in WebDriver JavaScript,
var elm = $("#myid");
browser.executeScript("arguments[0].click();", elm.getWebElement());

This issue has raised questions concerning the difference between the JavaScript click and the WebDriver click. Many are also eager to know why it is possible to Click through JavaScript when it seems not to work in WebDriver click and thus brings thoughts as to the possibility of a risk attached.

JavaScript click () vs WebDriver click ()

For the WebDriver, when the click works, the simulation of real user experience on a browser is attempted. For clarification, let’s assume an element A represents a button that displays ‘Click me’, and another element B is categorized as a div element that is characteristically transparent with its dimensions. After you instruct the WebDriver to click A, the instruction will be transmitted, and the click will be simulated, so that element B is the first recipient of the click. This happens because element B covers element A. That is, any user who tries to click on element A would have to first go through element B. Element A may receive the click, or not, depending on the way element B handles the instruction. As the case may be, the actions of the WebDriver at this time are identical to a situation where a real user attempts to click on element A.

In the case of JavaScript click () to Click element A, it does not duplicate precisely what happens when a real user attempts to click element A like WebDriver does. Instead, JavaScript transmits the click instructions directly to element A without any interference by element B.

Posted on Leave a comment

How to resolve ElementNotInteractableException: Element is not visible in Selenium webdriver

ElementNotInteractableException is one of the few notable exceptions encountered in the Selenium WebDriver. This W3C exception is thrown to outline how, regardless of the presence of an element in the HTML DOM, it still can’t be interacted with. This is evident in the inability to click or send keys, functions which make running the Selenium WebDriver possible. There are many root causes which may be attached to this problem; the prominent ones are element invisibility or non-display and hidden element behind another. Through this article, we will outline the few steps you can take to rectify this issue.

Temporary Overlay of other WebElement over the WebElement of our interest

When this problem has been identified as the root cause, the most effective way to resolve this is to execute ExplicitWait by combining WebDriverWait and ExpectedCondition as invisibilityOfElementLocated. A sample of this is analyzed below:

WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("xpath_of_element_to_be_invisible")));
driver.findElement(By.xpath("xpath_element_to_be_clicked")).click();

Another way to go about solving this problem is by approaching it on a more granular level by using ExpectedCondition as elementToBeClickable as opposed to using ExpectedCondition as invisibilityOfElementLocated. This is analyzed below:

WebDriverWait wait1 = new WebDriverWait(driver, 10);
WebElement element1 = wait1.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath_of_element_to_be_clicked")));
element1.click();

Permanent Overlay of other WebElement over the WebElement of our interest

The best solution for this type of problem is by casting the WebDriver instance as if the overlay is a permanent one. In this case, we have to cast the WebDriver instance as JavascriptExecutor followed by a click operation. This step is analyzed below:

WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);

Other general ways of solving the ElementNotInteractableException include:

  • Waiting until an element is visible/clickable
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.visibilityof(element));
wait.until(ExpectedConditions.elementTobBeClickable(element));
  • Scroll until the element is within the display
Actions action = new Actions(driver):
action.moveToElement(element);
  • Utilizing JS Executor to interact with the DOM
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("var element = document.querySelector('locator');element.value = 'whatever';")
Posted on Leave a comment

How to Take Screenshots with Selenium WebDriver

It is a well-known concept that Automated testing is most important during the testing stage of a software. However, due to a range of failures encountered during the testing process, it is easy for anyone to get discouraged and uncomfortable with the prospect of re-test in an entire script. The introduction of screenshot in the Selenium WebDriver helps in detecting test failures on the spot. In this article, you will learn the different ways to take a screenshot with the Selenium WebDriver.

Screenshots Using Selenium WebDriver

There are three steps required to follow before you can successfully take a screenshot in Selenium. The steps are analyzed below:

1 Convert web  driver object  to TakeScreenshot

TakesScreenshot scrShot =((TakesScreenshot)webdriver);

2 Utilize the getScreenshotAs method to produce an image file

File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

3 Copy file to desired location.

Programmers should note that the Selenium version 3.9.0 and above does not include the Apache Commons IO JAR. This can, however, be downloaded and integrated into your Work. Below is an example of how to take Screenshots with Selenium WebDriver. In the example, we will take a screenshot of https://testup.io/ and save it as C:/Test.png

package TestupTakeScreenshot;

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class TestupTakeScreenshot {
    @Test
    public void testTestupTakeScreenShot() throws Exception{

WebDriver driver ;
        System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
        driver = new FirefoxDriver();
        //goto url
        driver.get("https://testup.io/");
        //Call take screenshot function
        this.takeSnapShot(driver, "c://test.png") ;    
    }
    /**
     * This function will take screenshot
     * @param webdriver
     * @param fileWithPath
     * @throws Exception
     */
    public static void takeSnapShot(WebDriver webdriver,String fileWithPath) throws Exception{
        //Convert web driver object to TakeScreenshot
        TakesScreenshot scrShot =((TakesScreenshot)webdriver);
        //Call getScreenshotAs method to create image file
                File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
            //Move image file to new destination
                File DestFile=new File(fileWithPath);
                //Copy file at destination
                FileUtils.copyFile(SrcFile, DestFile);
    }
}
Posted on Leave a comment

Ways to deal with #document under iframe

When looking out for ways to deal with #document under iframe, it is essential to consider iframe as a build that is enclosed within another document or data file into an HTML to display the embedded data or code in a sub-window within the current window of the browser. It is, therefore, impossible to treat one document as independent of another.

The Ultimate Way Out

An inline frame element is usually found in this form:

<iframe src="URL" more attributes>
alternative content for browsers which do not support iframe
</iframe>
The documents which are referred to by the URL in a particular subwindow

The documents which are made according to the URL in a sub-window are displayed with either vertical/horizontal scroll bars in browsers that support inline frame. These types of browsers display regardless of the contents of the inline frame element, while browsers that don’t support the inline frame take the opposite action by processing the contents of the iframe element with the assumption that the <iframe…> and </iframe> tags were absent. This leads to the conclusion that the contents of the iframe elements are essential regardless of the negligence by a few browsers.

Using JavaScript to Communicate iframe

JavaScript can be utilized in communicating with the iframe and the documents within it. The first of the few steps is to acquire the references to the iframe, the properties, and finally, the contents within it. To acquire the references to an iframe, you should use the getElementById. The references acquired can then be used to edit the properties found on the iframe.

// reference to iframe with id 'ifrm'
var ifrm = document.getElementById('ifrm');
ifrm.style.width = '400px'; // set width
ifrm.src = 'newpage.html'; // set src to new url

Other properties entailed in the iframe element include both the contentWindow and contentDocument properties. References to the iframe documents window and objects can be acquired from these properties using JavaScript. This step is analyzed below:

// using reference to iframe (ifrm) obtained above
var win =  ifrm.contentWindow; // reference to iframe's window
// reference to document in iframe
var doc = ifrm.contentDocument? ifrm.contentDocument:
ifrm.contentWindow.document;
// reference to form named 'demoForm' in iframe
var form = doc.getElementById('demoForm');

Immediately the references to the window and document have been acquired; it is possible to gain access to any object or property bound within the iframe document.

Posted on Leave a comment

How to Fix “Are you sure you want to do this?” Error in WordPress

Getting “Are you sure you want to do this” error in WordPress? You are in the right place as this article will reveal how to fix the issue with few simple steps.

Check Site Security

Most times, you get the error when you try to finalise an action that requires specific user permissions, but WordPress is unable to verify that you have access to do that. WordPress makes use of security tokens called nonces. If WordPress can’t verify these tokens, the error will display.

Generate new Security Keys

To fix this error, you can generate new security keys using the  WordPress Security Key Generator. What you need to do is to copy the whole output and paste it in your wp-config.php file.

Plugin or Theme Upload Error

If you get the error when trying to upload a plugin or theme, there may be a problem with the zip file. To fix the issue, take the following steps:

  1. Go to cPanel > File Manager
  2. Look for the public_html folder and open the wp-content folder.
  3. If you are uploading a plugin, go to the plugin folder. If you are uploading a theme, open the theme folder. Upload your plugin or theme zip file in there and unzip the file. After that, delete the zip file.
  4. Go to the wp-admin dashboard to activate the theme or plugin. That’s all!

Other Solutions

The other solutions you can try are popular actions like:

  • Increasing your PHP Memory Limit
  • Clearing caches and cookies
  • Deactivating theme and plugins
Posted on Leave a comment

Customizing WordPress with Elementor – How to Start

WordPress is an open-source PHP-based CMS with a series of great plugins and extensions which have been developed over the years to make it one of the best and most popular CMS platforms on the planet. Elementor is one of those groundbreaking WordPress builder plugins/tools. In this article, you will learn more about the Elementor plugin.

Why Elementor?

Elementor offers great and advanced tools to design and bring the life and beauty out of any WordPress website. With its extensions, the power of Elementor appears unmatched by other rivals. Some of the features that distinguishes Elementor include:

  • All-in-One Solution that controls every aspect of your web design workflow from one place.
  • Visual Design is simple, powerful, and flexible. It offers 100% visual design.
  • Faster Performance. You can build websites that load faster and speed up the building process.

What is the structure?

In this section, you will learn about the structures of the following on Pages, Posts, Templates with illustrative images on Elementor.

Pages

It is easy to build and design pages on Elementor with its thousands of extensions and user-friendly compatible plugins. See photo below.

Posts

Posting has also been made easy and more robust using this plugin. Elementor offers more capability for bloggers to post without adding plenty of third parties plugins as these are already embedded in the Elementor plugin. More features are available on the Pro version.

Themes

Just like other page builders, some WordPress themes are built with Elementor compatibility. When looking for themes to purchase online, be sure to also look out for themes built in this format as some themes may even come with ELEMENTOR pro in the purchase download. See a list of Elementor friendly themes from ThemeForest.

Also included is the theme builder feature that lets you customize anything on your website.

Extensions and Addons

As stated earlier, over 100s of thousands of extensions are available pre-built both with the follow-come plugin and external ones. These extensions are great, as they minimize the work of your website loading multiple plugins, thus optimizing your website speed and, ultimately, SEO. See a list of great extensions here.

Click here to see all features of Elementor categorized appropriately.

What does Elementor Pro offer?

Free vs Pro

Well, just like every other thing you buy on the planet. The PRO means more features and Premium services. Elementor Pro does not fail to impress. Every feature is worth it on the pro. See below an image illustration of features:

Click here to get started on the Elementor Pro.

Headers and footers

It is crucial to know how to build headers and footers using the Elementor pro. You can check out an easy walkthrough by Elementor here. You can also see this YouTube video for a visual guide.

Global Elements (Widget)

It gives you full control over a specific widget that is shown in multiple places on your site. Editing it in one place will update the others. Here Is a documentation on how this is done.

Conclusion

Elementor Pro offers you top-notch page building tools for all WordPress sites to give you that all-in-one package without compromising website speed and functionalities caused by multiple installed plugins. It is one of the best in the web industry today and every WordPress expert’s best friend.

Posted on Leave a comment

Fixing Syntax Error in WordPress

A syntax error usually occurs when you make a mistake in your code. With this error, the compiler cannot process (parse) the file. Therefore, it fails to display your website. In this short piece, you will learn how to fix the syntax error.

Steps to take to Fix the Syntax Error

  1. Go to the cPanel.
  2. Click on File Manager and locate the corrupted file named in the error. Right-click the file and select Edit.
  3. Head to the line number specified in the error and check for errors like missing semicolons, punctuation, tags, and brackets.
  4. After correcting the error, click Save & Close. Then, reload your site and confirm the error no longer come up.

In some instances, you can fix syntax errors by deleting the line that caused the error and rewriting, if necessary. For example, if there is a comment missing escape characters and has been interpreted as code, deleting the line completely will fix the error. However, you need to be careful when you delete a line so as not to cause another issue. For instance, you cannot delete a line used for computing a variable’s value. If you do, you will need to re-write the correct version of the code.

Conclusion

While getting syntax or parse errors can be so frustrating, you can fix the errors by simply determining the corrupted file and modifying it. For more tutorials on fixing issues encountered in WordPress, check out our blog and resources at Testup.