-
PYTHON > contrôler Firefox avec selenium
- Run tests in parallel on multiple test machines to speed up test execution
- Test across a range of environments, including different operating systems, browsers, and devices
- Report and analyze test results in real time
- Work together on testing projects with collaboration and sharing tools
- Easily adjust the number of test machines and other testing resources for better scalability and flexibility
- Id and attribute example:
- Class and attribute Example:
- Matching a prefix (Starts with: ^): Locate the web element using the substring that starts with a certain value.
- Matching a suffix (Ends with: $): Locate the web element using the substring that ends with a certain value.
- Matching a substring (contains: *): Locate the web element by matching the substring.
INSTALLATION
Pour fonctionner avec Firefox, installer le moteur de rendu geckodriver :
Puis, installer selenium
python3 -m pip install selenium
Hello world
Importer le webdriver, puis lancer Firefox, ouvrir une page web, puis envoyer coucou dans nav-search
# coding=utf-8 from selenium import webdriver driver = webdriver.Firefox() driver.get("https://dev.to") driver.find_element_by_id("nav-search").send_keys("coucou")
FirefoxOptions :
from selenium.webdriver.firefox.options import Options as FirefoxOptions options = FirefoxOptions() options.add_argument("--headless") driver = webdriver.Firefox(options=options) driver.get("https://pythonbasics.org")
Fermer l’explorateur
browser.close()
SÉLECTIONNER UN ÉLÉMENT
find_element ou find_elements
<input type="text" name="passwd" id="passwd-id" />
from selenium.webdriver.common.by import By el = driver.find_element(By.ID, "passwd-id") el = driver.find_element(By.NAME, "passwd") el = driver.find_element(By.XPATH, "//input[@id='passwd-id']") el = driver.find_element(By.CSS_SELECTOR, "input#passwd-id")
CLAVIER DONNÉES
from selenium.webdriver.common.keys import Keys el.clear() el.send_keys("pycon") el.send_keys(Keys.RETURN)
CSS Selectors
A CSS Selector is a combination of an element selector and a value which identifies the web element within a web page. They are string representations of HTML tags, attributes, Id and Class. As such they are patterns that match against elements in a tree and are one of several technologies that can be used to select nodes in an XML document.
Today we’ll cover simple CSS selectors, then more advanced, then pseudo-classes, which are essentially powerful, built-in matching functions that reduce a search to just what you are looking for.
I: Simple
XPATH
XPath: //div[@id='example'] -> div#example XPath: //input -> input
Direct Child
A direct child in XPATH is defined by the use of a “/“, while on CSS, it’s defined using “>”.
XPath: //div/a -> div > a
Child or Sub-Child
If an element could be inside another or one of its children, it’s defined in XPATH using “//” and in CSS just by a whitespace.
XPath: //div//a CSS: div a
Class
For classes, things are pretty similar in XPATH: “[@class='example']” while in CSS it’s just “.”
XPath: //div[@class='example'] CSS: .example
II: Advanced
Next Sibling
This is useful for navigating lists of elements, such as forms or ul items. The next sibling will tell selenium to find the next adjacent element on the page that’s inside the same parent. Let’s show an example using a form to select the field after username.
<form class = "form-signin" role = "form" action = "/index.php" method = "post"> <h4 class = "form-signin-heading"></h4> <input type = "text" class = "form-control" id = "username" name = "username" placeholder = "username" required autofocus></br> <input type = "password" class = "form-control" id = "password" name = "password" placeholder = "password" required> <p> <button class = "btn btn-lg btn-primary btn-block radius" type = "submit" name = "login">Login</button> </form>
Let’s write an XPath and css selector that will choose the input field after “username”. This will select the “alias” input, or will select a different element if the form is reordered.
XPATH: //input[@id='username']/following-sibling:input[1] CSS: #username + input
Attribute Values
If you don’t care about the ordering of child elements, you can use an attribute selector in selenium to choose elements based on any attribute value. A good example would be choosing the ‘username’ element of the form above without adding a class.
We can easily select the username element without adding a class or an id to the element.
XPATH: //input[@name='username'] CSS: input[name='username']
We can even chain filters to be more specific with our selectors.
XPATH: //input[@name='login'and @type='submit'] CSS: input[name='login'][type='submit']
Here Selenium will act on the input field with name="login" and type="submit"
Choosing a Specific Match
CSS selectors in Selenium allow us to navigate lists with more finesse than the above methods. If we have a ul and we want to select its fourth li element without regard to any other elements, we should use nth-child or nth-of-type. Nth-child is a pseudo-class. In straight CSS, that allows you to override behavior of certain elements; we can also use it to select those elements.
<ul id = "recordlist"> <li>Cat</li> <li>Dog</li> <li>Car</li> <li>Goat</li> </ul>
If we want to select the fourth li element (Goat) in this list, we can use the nth-of-type, which will find the fourth li in the list. Notice the two colons, a recent change to how CSS identifies pseudo-classes.
CSS: #recordlist li::nth-of-type(4)
On the other hand, if we want to get the fourth element only if it is a li element, we can use a filtered nth-child which will select (Car) in this case.
CSS: #recordlist li::nth-child(4)
Note, if you don’t specify a child type for nth-child it will allow you to select the fourth child without regard to type. This may be useful in testing css layout in selenium.
CSS: #recordlist *::nth-child(4)
In XPATH this would be similar to using [4].
Sub-String Matches
CSS in Selenium has an interesting feature of allowing partial string matches using ^=, $=, or *=. I’ll define them, then show an example of each:
^= Match a prefix CSS: a[id^='id_prefix_'] A link with an “id” that starts with the text “id_prefix_” $= Match a suffix CSS: a[id$='_id_sufix'] A link with an “id” that ends with the text “_id_sufix” *= Match a substring CSS: a[id*='id_pattern'] A link with an “id” that contains the text “id_pattern”
—
What is the Selenium Click Command?
Selenium’s click() command emulates a mouse click operation for any interactive UI element (links, buttons, checkboxes, radio buttons). Simulating mouse clicks using Selenium can not only save crucial manual testing effort, but also help to identify bugs in your application.
How to Use the Selenium Click Command
Here’s an example of the Selenium click() command:
The following Java command invocation simulates a click on a button (with the HTML ID “clickable”)
clickable = driver.findElement(By.id("clickable")); clickable.click()
Form submissions and buttons are the most common drivers of “state change” in an application, and they tend to be the most important steps in any test. It’s after the click that the assertions need to be made, to examine the resulting page changes for actual-vs-expected behavior.
However, the Selenium click() command only covers the left mouse button, the most common kind of mouse interaction. What happens when you need to click with the right mouse button?
Advanced Click Techniques: Sending a Right-Click Mouse Event
Sometimes you’ll run into an app that has functionality hidden behind a right-click menu (e.g., a context menu). These tend to be system-level menus that are untouchable by Selenium’s default methods. So how do you get to them?
By leveraging Selenium’s mouse actions library, you can issue a right-click command (a.k.a. a context_click).
Let’s use a right-click example from the-internet:
This page will render a custom context menu when we right-click on a specific area of the page. For example:
Clicking the context menu will trigger a JavaScript alert that says, ”You selected a context menu.”
driver.navigate() .to("http://the-internet.herokuapp.com/context_menu"); WebElement clickable = driver.findElement(By.id("hot-spot")); new Actions(driver) .contextClick(clickable) .perform(); Alert alert = new WebDriverWait(driver, Duration.ofSeconds(2)) .until(ExpectedConditions.alertIsPresent()); Assertions.assertEquals("You selected a context menu", alert.getText());
First, navigate to the page and find your right-clickable element. Once you have it, send the actions-based contextClick(). After you send the event, wait for an alert to appear, then confirm that the text message appears as expected.
By following this example and looking at Selenium’s Actions API documentation, you should be able to send mouse actions like click, double-click, right-click, click-and-hold, back-click, and more. In addition to standard mouse events, the Selenium Actions API also provides support for mouse wheel, pen actions, and just about anything you’d need to do with a keyboard.
Getting Started with the Selenium Click Command
These examples have shown the basics of how to send mouse events. In your own test code, be sure to abstract out complicated code like actions when you’re working with common web elements, so that testers encountering your code in the future can make changes quickly. There are many ways to simulate various mouse events, and this article didn’t touch on any more than the basics. Be sure to check out the official Selenium documentation for more details.
—
Getting Started with Selenium
In addition to installing Python, you have to install the Selenium API for Python using pip.
Open your terminal and run the following command:
pip install selenium
After installing Selenium, you can begin writing your script.
The first step is to create a new Python script. Open your preferred text editor and create a new file called selenium_test.py. Then, import the Selenium library by adding the following lines of code to your script:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from time import sleep
Next, create a new instance of the webdriver class with additional Options. This class represents the web browser that will be used to run your tests. In this example, you’ll be using the Chrome web browser, so you need to create a new instance of the Chrome class, and the Options class described above allows web drivers to run a browser instance with additional capabilities.
The example below sets the driver to start the web browser without the DevTools prompt:
options = Options() options.add_experimental_option("excludeSwitches", ["enable-logging"]) driver = webdriver.Chrome(options=options)
Setting Options is not mandatory, but it makes the output window much cleaner. You will, however, need to include the argument that the Chrome class should take a path to WebDriver, as Selenium uses it to initiate the browser window and perform the tests.
With your driver object set up, you can start the testing process by writing a simple script to test the title of a web page. For this tutorial, you’ll run your tests on the Sauce Labs demo site, SwagLabs.
In your code editor, write the following code in selenium_test.py:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from time import sleep # Set options for not prompting DevTools information options = Options() options.add_experimental_option("excludeSwitches", ["enable-logging"]) print("testing started") driver = webdriver.Chrome(options=options) driver.get("https://www.saucedemo.com/") sleep(3) # Get page title title = driver.title # Test if title is correct assert "Swag Labs" in title print("TEST 0: `title` test passed") # Close the driver driver.quit()
To run this test, open your terminal and run the following command:
python selenium_test.py
Running the command above should produce the following output:
testing started TEST 0: `title` test passed
If the output does not return an AssertionError, it indicates that the tests passed successfully and the title of the demo website is correct.
Extending the Test Script
In this section, you’ll extend your script to test the login functionality of the demo site. To do this, you’ll need to grab the input boxes and submit button of the web page by inspecting its site elements. Right-click the page and select the Inspect menu option to see an Elements tab in the right pane of the browser window, as shown in the image below:
This pane is called DevTools. With it opened, grab the id or class attributes of the input boxes on the web page, depending on the elements you want to test. Click the icon in the top-left corner of the DevTools pane, then select elements on the web page. The corresponding code of the element will automatically highlight in the DevTools pane, as shown in the image below:
Testing Login Functionality
To test the login functionality of the demo site, Selenium will locate the username and password fields and populate them with appropriate credentials. You’ll then programmatically click the login button, which can easily be done after selecting the button using its id.
To begin writing the script, create a new file named test_demo.py. Add the following code to import the required modules that will be used by the script:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from time import sleep
After importing the necessary modules, you must set the Options class for your webdriver and initiate Chrome WebDriver, as shown in the code below. This webdriver is responsible for rendering the browser window:
# Set options for not prompting DevTools information options = Options() options.add_experimental_option("excludeSwitches", ["enable-logging"]) print("testing started") driver = webdriver.Chrome(options=options)
Next, you must add the code below to open the demo website and begin your testing process. After opening the web page, the execution of the script halts for three seconds using the sleep(3) function so that all the elements in the web page load completely in the browser:
driver.get("https://www.saucedemo.com/") sleep(3)
In the code block below, you use find_element() and the By class in conjunction to grab the username and password fields. The By class is used to easily locate elements on the web page through class, id, and xpath. After getting the fields, you use the send_keys() function to populate the fields with credentials. You then use the find_element() function to get the login button and use the click() function for the button to initiate the login process:
# Find element using element's id attribute driver.find_element(By.ID, "user-name").send_keys("standard_user") driver.find_element(By.ID, "password").send_keys("secret_sauce") driver.find_element(By.ID, "login-button").click() sleep(5)
To test whether the login was successful, you can check if the resulting web page loads as expected. In the code below, you assert that the element with title as its class attribute contains the string "products". If the assert is wrong, your string will throw an AssertionError. After performing the test, you have to quit the driver to release any memory held by the browser window:
text = driver.find_element(By.CLASS_NAME, "title").text # Check if login was successful assert "products" in text.lower() print("TEST PASSED : LOGIN SUCCESSFUL") # Close the driver driver.quit()
Running the above code should produce the following output:
$ python test_demo.py testing started TEST PASSED : LOGIN SUCCESSFUL
As you can see, the test passed, which means that the demo site is working as expected.
Note: Using sleep is generally not considered a best practice, and was done here for simplicity’s sake. The WebDriverWait command is the proper way to go.
Testing Add/Remove Buttons
In this section, you’ll extend your script to include two more tests. These will test the buttons for adding and removing items from the cart.
Open the test_demo.py file and add the code below before the driver.quit() statement. First, add a test that grabs all the "Add to Cart" buttons and clicks a certain number of buttons:
print("testing add to cart") add_to_cart_btns = driver.find_elements(By.CLASS_NAME, "btn_inventory") # Click three buttons to make the cart_value 3 for btns in add_to_cart_btns[:3]: btns.click()
The code above uses the find_elements() function instead of find_element() to grab a list of elements with btn_inventory as the CLASS_NAME.
Now, you have to test the assertion that the cart_value is three after clicking the three buttons in add_to_cart_btns:
cart_value = driver.find_element(By.CLASS_NAME, "shopping_cart_badge") assert "3" in cart_value.text print("TEST PASSED : ADD TO CART", "\n")
In the above code, you retrieve the element with the class name shopping_cart_badge and check if it contains the text "3″, which would indicate that three items were successfully added to the cart.
To test the remove from cart button functionality, add the following code to your Selenium script:
print("testing remove from cart") remove_btns = driver.find_elements(By.CLASS_NAME, "btn_inventory") for btns in remove_btns[:2]: btns.click() assert "1" in cart_value.text print("TEST PASSED : REMOVE FROM CART", "\n")
The code uses the driver.find_elements method again to locate all the btn_inventory elements on the page, and clicks the first two of them. It then checks if the shopping_cart_badge element contains the text "1″, which would indicate that two items were successfully removed from the cart. The code prints a success message if both of these checks pass.
The script above runs on your machine with a local browser, which is sufficient for learning the basics. However, testing an entire website locally isn’t scalable--if it’s on your work laptop, you can’t do anything else while the tests are running. This is one of the reasons why testing should be done on a cloud-based testing platform like Sauce Labs.
A cloud-based testing platform lets you manage, run, and analyze the results of tests on a wide range of browsers and platforms on remote servers rather than on your local hardware. It also ensures that the results are reliable and consistent, even when running large numbers of tests in parallel.
A solution like Sauce Labs allows you to:
To use Sauce Labs for your current Selenium script, you have to make some changes to your file. Before making any changes, copy the on-demand URL from the User Settings section in your Sauce Labs dashboard.
Sauce Labs provides hundreds of devices and browser versions on which to run your tests. It also offers a platform configurator to generate custom options for your Selenium WebDriver.
Copy these options and paste them into your Selenium script. Next, supply the build ID and test name of your choice and replace the url with the on-demand URL you copied earlier. The final file should look something like this:
<script src="https://gist.github.com/vivekthedev/f8832087dd4da87f6b63750c8d0b4998.js"></script>
Run the test using the command below:
python test_demo.py
You should get the output below to show that the test worked as expected:
testing started TEST PASSED : LOGIN SUCCESSFUL testing add to cart TEST PASSED : ADD TO CART testing remove from cart TEST PASSED : REMOVE FROM CART
You can also get additional information about the tests from Sauce Labs, including screenshots, video recordings, logs, and command history. Go to the Test Results section in your Sauce Labs dashboard to see the in-depth test analysis.
Wrapping Up
In this tutorial, you learned how to use Selenium with Python to run tests on web applications. You tested a demo site by asserting its title and then expanded on the script to test the internal functionality of the web application.
You also learned how to adapt your script to work on the cross-browser cloud testing platform Sauce Labs, and you ran a Selenium script using Sauce Labs’ built-in platform configurator.
Using a cloud-based cross-browser testing platform like Sauce Labs makes it easy to run tests on a wide range of browsers and platforms. Sauce Labs’ reliable and stable platform also helps ensure that test results are reliable and consistent, even for large numbers of tests.
—
Writing the Test Script Using Python Code
A browser driver proxy: Install the most recent browser driver that works with your OS and browser version. You can either hard code the location of the browser driver or set up the environment path using driver management software. For the purposes of this tutorial, we’ll import it straight from the WebDriver, as demonstrated below:
from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.edge.service import Service as EdgeService from selenium.webdriver.firefox.service import Service as FirefoxService from selenium.webdriver.ie.service import Service as IEService from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.firefox import GeckoDriverManager from webdriver_manager.microsoft import EdgeChromiumDriverManager from webdriver_manager.microsoft import IEDriverManager
Now, you can perform cross-browser testing with Python code.
Create a file called “test.py” on your preferred IDE, then paste the following code to test different browsers (like Firefox, Chrome, Internet Explorer, Safari, and Microsoft Edge):
from selenium import webdriver from selenium.webdriver.common.by import By import unittest class SeleniumCrossBrowserTest(unittest.TestCase): def setUp(self): ''' Start the Selenium WebDriver in a browser of your choice. We use Chrome here but you can replace Chrome with one of the other options. ''' # self.driver = webdriver.Safari() # self.driver = webdriver.Edge() # self.driver = webdriver.Firefox() self.driver = webdriver.Chrome() def tearDown(self): '''Quit the browser session once you are finished''' self.driver.quit() def test_sauce_labs(self): ''' The setUp function initializes the right virtual machine browsers on Sauce Labs Tests for a[text()] elements within the Sauce Labs' Homepage Platforms and Pricing ''' self.browser.get("https://www.saucelabs.com") element = self.browser.find_element(By.XPATH, '//a[text()="Platform"]') self.assertTrue(element.is_displayed()) element.click() pricing_link = self.browser.find_element(By.XPATH, '//a[text()="Pricing"]') self.assertTrue(pricing_link.is_displayed()) if __name__ == '__main__': unittest.main(verbosity=2)
II. Running Tests on Sauce Labs
Once you have your test script coded as above, you need to replace your environment variables with actual Sauce Labs credentials (a username and secret key). First, sign up for a Sauce Labs account if you don’t already have one.
Next, get your username and access key. You will use this access key in combination with your username to interact with Sauce Labs.
Then, assign the environment credentials within the code:
Username = =os.environment.get('SAUCE_USERNAME',None) #your sauce labs username Access_key = os.environment('SAUCE_ACCESS_KEY',None) #your sauce labs secret key URL="http://{}:{}@ondemand.saucelabs.com:80/wd/hub".format( sauce_username, sauce_key )
Now the tests look like this:
from selenium import webdriver from selenium.webdriver.common.by import By import unittest import os class SauceCrossBrowserTest(unittest.TestCase): def setUp(self): ''' Start the Selenium WebDriver as a RemoteDriver connecting to Sauce Labs. ''' username = os.environ.get('SAUCE_USERNAME') access_key = os.environ.get('SAUCE_ACCESS_KEY') caps = webdriver.ChromeOptions() sauce_caps = { "browserName": "Chrome", "browserVersion": "latest", "platformName": "Windows 10" } caps.set_capability('sauce:options', sauce_caps) sauce_url = "https://{}:{}@ondemand.us-west-1.saucelabs.com/wd/hub/".format(username, access_key) self.driver = webdriver.Remote( command_executor=sauce_url, options=caps ) def tearDown(self): '''Quit the browser session once you are finished''' self.driver.quit() def test_sauce_labs(self): ''' The setUp function initializes the right virtual machine browsers on Sauce Labs Tests for a[text()] elements within the Sauce Labs' Homepage Platforms and Pricing ''' self.driver.get("https://www.saucelabs.com") element = self.driver.find_element(By.XPATH, '//a[text()="Platform"]') self.assertTrue(element.is_displayed()) element.click() pricing_link = self.driver.find_element(By.XPATH, '//a[text()="Pricing"]') self.assertTrue(pricing_link.is_displayed()) if __name__ == '__main__': unittest.main(verbosity=2)
Now, it’s time to run the test. To do so, run the following Python code file in the terminal:
python test.py
To view the results of your cross-browser testing, simply log back in to your Sauce Labs account and navigate to the Sauce Labs Dashboard.
Getting Started with Selenium Cross-Browser Testing on Sauce Labs
In this article, we discussed cross-browser testing and explained how to automate it with Python and Selenium. Cross-browser testing with Selenium ensures that your web application is compatible with all major browsers and that it provides a consistent user experience.
Due to the growing number of web browsers and sophisticated cloud applications, organizations need a more advanced cloud-based testing platform with increased processing capacity. The Sauce Labs platform provides more automation, greater test coverage, and overall application efficiency. It enables Selenium-based web application and cross-browser testing via the Sauce Labs cloud solution. For more information, you can check out our comprehensive Selenium on Sauce Labs documentation.
—
How to iterate through child elements of a div selenium
#Scrape the user table Username = driver.find_elements(By.XPATH, value="//td[@role][1]") Role = driver.find_elements(By.XPATH, value="//td/span[@tooltipkey]") for i in range(len(Username)): if Username[i].text in userdict: UserGet = userdict.get(Username[i].text) print("Company Name|F|DS0000|Company Role|" + UserGet + "|enabled|||" + Role[i].text) List.append("Company Name|F|DS0000|Company Role|" + UserGet + "|enabled|||" + Role[i].text) else: print(Username[i].text + " Not in User Dictionary")
—
Get all child elements of a parent element
Initially, you have to get the parent element. Then using parent element we can retrive the child elements as shown below:
WebElement parentElement = driver.findElement(By.id("something"));List<WebElement> allChildElements = parentElement.findElements(By.xpath("*"));
Here, ‘allChildElements’ contains child elements.
To print the child Size, you can use:
allChildElements.size();
—
Selenium - Find all elements of a web page [Java]
We can use WebElement.findElements method to get list of all the elements inside Web-Page.
All Xpath
List<WebElement> el = driver.findElements(By.xpath(“//*”));
All Ids
List<WebElement> el = driver.findElements(By.id(“//*[@id]”));
All CSS
List<WebElement> el = driver.findElements(By.cssSelector(“*”));
All NAME
List<WebElement> el = driver.findElements(By.xpath(“//*[@name]”));
All LINK TEXT
List<WebElement> el = driver.findElements(By.xpath(“//a[@href]”));
ALL CLASS
List<WebElement> el = driver.findElements(By.xpath(“//*[@class]”));
Here, ‘el’ contains the list of all Elements within the webpage.
To, get the size of elements you can use:
System.out.println(el.size());
This will print the size of web-elements.
—
What is JavaScriptExecutor ?
JavaScriptExecutor is an interface provided by Selenium Webdriver and provides a way to execute JavaScript in Webdriver. This interface provides a way to run JavaScript in the selected window or current location. JavaScriptExecutor is an interface that can be used in any language that supports the Selenium framework. Since
JavaScriptExecutor is a Selenium interface, no additional plugins or add-ons are required. You can use it directly fromimport package org.openqa.selenium.JavascriptExecutor.
Selenium provides two JavaScriptExecutor Methods:
a) executeAsyncScript
This method executes an asynchronous snippet of JavaScript in the context of the currently selected window or frame in Selenium. Here the script will also run as the body of the anonymous function. The main difference between executeScript and executeAsyncScript is that scripts called with executeAsyncScript must use a callback function to indicate that execution is complete.
b) executeScript
For the executeScript method JavaScript Executor is currently selected to execute JavaScript as a reference to a window or frame. The script inside the method runs in the body of the unnamed function.
The document in the script is used to point to the current document. Also, when the script finishes running, the local variables will not be displayed. But we need global variables.Both methods allow us to use the `return` keyword to return a value and store it in a variable. The data types that can be returned are:
~Long
~String
~Boolean
~List
~WebElementSyntax
JavascriptExecutor javascript = (JavascriptExecutor) driver; javascript.executeScript(Script,Arguments);
Script — Script that needs to execute.
Arguments — Arguments to the script. Not Compulsory.import org.openqa.selenium.JavascriptExecutor; public class Javascript_Demo{ public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://www.site.com"); // Javascript executor JavascriptExecutor js = (JavascriptExecutor) driver; //executeScript method [Return the height of webpage] String java_str = (String) js.executeScript(""return document.body.scrollHeight;""); System.out.println(java_str); driver.quit(); } }
—
Selenium for Full Page Screenshots without changing devicePixel ratio
Screenshot usingAShot(), without changing devicePixel ratio:
Here, object is created of output which stores the value of device’s pixel. And then we convert it into the string variable then it into the float value which is windowDPR.
Object output = ((JavascriptExecutor) webDriver).executeScript("return window.devicePixelRatio"); String value = String.valueOf(output); float windowDPR = Float.parseFloat(value);
Then using Ashot() with 100 speed scrolling. and convert myScreenshot variable to the PNG.
Screenshot myScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(ShootingStrategies.scaling(windowDPR),100)).takeScreenshot(webDriver);ImageIO.write(myScreenshot.getImage(),"PNG",new File("Screenshot.png"));
Then output is “Screenshot.png” you can use the path before to store at absolute location.
If you want to take full screenshots without fixed or sticky menu. I have created that demo. Check out the other Posts for that.
—
driver.get("https://www.site.org/"); // Find an element WebElement element=driver.findElement(By.xpath("//ul[@id='hslider']")); // Find the child element List<WebElement> list = element.findElements(By.xpath("./child::*")); // iterate the list for ( WebElement i : list ) { // Print the child elements System.out.println(i.getText()); } // Close the driver driver.close();
—
CSS Selector in Selenium: Locate Elements with Examples
Also Read: CSS Selectors Cheat Sheet (Basic & Advanced)
1. ID
In CSS, we can use “#” notation to select the “id” attribute of an element.
driver.findElement(By.cssSelector(“<tagname>#<id value>”)); driver.findElement(By.cssSelector(“#<id value>”)); driver.findElement(By.cssSelector(“<tagname>[id=’<id value>’]”));
To locate the “Offers” tab on the BStackDemo application, the following are the CSS selectors with id.
driver.findElement(By.cssSelector("a#offers")); driver.findElement(By.cssSelector("#offers")); driver.findElement(By.cssSelector("a[id='offers']"));
2. Class
In CSS, we can use “.” notation to select the “class” attribute of an element.
driver.findElement(By.cssSelector(“<tagname>.<class value>”)); driver.findElement(By.cssSelector(“.<class value>”)); driver.findElement(By.cssSelector(“<tagname>[class=’<class value>’]”));
To locate “BrowserStackDemo” on the BStackDemo application, following are the CSS selectors with class.
driver.findElement(By.cssSelector("a.Navbar_logo__26S5Y")); driver.findElement(By.cssSelector(".Navbar_logo__26S5Y")); driver.findElement(By.cssSelector("a[class='Navbar_logo__26S5Y']"));
Also Read: How to handle Action class in Selenium
3. Attribute
Apart from “id” and “class”, other attributes can also be used to locate web elements using CSS selector.
driver.findElement(By.cssSelector(“<tagname>[href=’<href value>’]”));
To locate the “Favourites” tab on BStackDemo application, following is the CSS selector with href attribute.
driver.findElement(By.cssSelector("a[href='/favourites']"));
There are other attributes too such as name, placeholder, title, type, etc which can be used to locate elements using CSS selector.
4. Combining Attributes
From above examples we understood how we can uniquely identify elements using CSS selectors, however sometimes, using only class/ id/ single attribute does not yield a unique locator for a given web element. In such cases, we can combine multiple attributes to fetch a unique locator.
If we want to locate WebElement “Offers” tab by just one attribute “href”, it gives 2 results which means it is not unique and pointing to 2 web elements on DOM. To make it unique we should also use “id” attribute.
driver.findElement(By.cssSelector(“<tagname>#<id value>[href=’<href value>’]”)); driver.findElement(By.cssSelector("a#offers[href='/offers']"));
If we want to locate the WebElement “Offers” tab by just class value, it gives 3 results, which means it is not unique and pointing to 3 web elements on DOM. To make it unique we should also use the “href” attribute.
driver.findElement(By.cssSelector(“<tagname>.<class value>[href=’<href value>’]”)); driver.findElement(By.cssSelector("a.Navbar_link__3Blki[href='/orders']"));
5. SubString
CSS Selectors in Selenium allows to match a partial String with the help of various symbols to represent the start, end and contents inside a text. Let us understand all the three ways with example for accessing BrowserStack logo on BStackDemo web application.
driver.findElement(By.cssSelector(“<tagname>[<attribute>^=’prefix of the string’]”)); a[class^='Navbar_logo_']
The complete String here is “Navbar_logo__26S5Y” therefore only the start of the String i.e: “Navbar_logo_” is considered to locate the element.
driver.findElement(By.cssSelector(“<tagname>[<attribute>$=’suffix of the string’]”)); a[class$='26S5Y']
The complete String here is “Navbar_logo__26S5Y” therefore only the end of the String i.e: “26S5Y ” is considered to locate the element.
driver.findElement(By.cssSelector(“<tagname>[<attribute>*=’substring’]”)); a[class*='logo_']
The complete String here is “Navbar_logo__26S5Y” therefore only a substring of the String i.e: “logo_ ” is considered to locate the element.
—