Selenium interview questions
29 questions with answers. 419 open jobs in India ask for Selenium.
Can a website detect when you are using Selenium with chromedriver?
Replacing
cdc_stringYou can use Vim or Perl to replace the
cdc_string inchromedriver. See the answer by @Erti-Chris Eelmaa to learn more about that string and how it's a detection point.Using Vim or Perl prevents you from having to recompile source code or use a hex editor.
Make sure to make a copy of the original
chromedriverbefore attempting to edit it.Our goal is to alter the
cdc_string, which looks something like$cdc_lasutopfhvcZLmcfl.The methods below were tested on
chromedriver version 2.41.578706.Using Vim
vim -b /path/to/chromedriverAfter running the line above, you'll probably see a bunch of gibberish. Do the following:
- Replace all instances of
cdc_withdog_by typing:%s/cdc_/dog_/g.dog_is just an example. You can choose anything as long as it has the same amount of characters as the search string (e.g.,cdc_), otherwise thechromedriverwill fail.
- To save the changes and quit, type
:wq!and pressreturn.- If you need to quit without saving changes, type
:q!and pressreturn.
- If you need to quit without saving changes, type
The
-boption tells vim upfront to open the file as a binary, so it won't mess with things like (missing) line endings (especially at the end of the file).Using Perl
The line below replaces all
cdc_occurrences withdog_. Credit to Vic Seedoubleyew:perl -pi -e 's/cdc_/dog_/g' /path/to/chromedriverMake sure that the replacement string (e.g.,
dog_) has the same number of characters as the search string (e.g.,cdc_), otherwise thechromedriverwill fail.Wrapping Up
To verify that all occurrences of
cdc_were replaced:grep "cdc_" /path/to/chromedriverIf no output was returned, the replacement was successful.
Go to the altered
chromedriverand double click on it. A terminal window should open up. If you don't seekilledin the output, you've successfully altered the driver.Make sure that the name of the altered
chromedriverbinary ischromedriver, and that the original binary is either moved from its original location or renamed.My Experience With This Method
I was previously being detected on a website while trying to log in, but after replacing
cdc_with an equal sized string, I was able to log in. Like others have said though, if you've already been detected, you might get blocked for a plethora of other reasons even after using this method. So you may have to try accessing the site that was detecting you using a VPN, different network, etc.From Stack Overflow: asked by Ryan Weinstein, answered by colossatr0n (CC BY-SA 4.0)
- Replace all instances of
Is there a way to get element by XPath using JavaScript in Selenium WebDriver?
You can use
document.evaluate:Evaluates an XPath expression string and returns a result of the specified type if possible.
It is w3-standardized and whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate
function getElementByXPath(path) { return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; } console.log( getElementByXPath("//html[1]/body[1]/div[1]") );<div>foo</div>https://gist.github.com/yckart/6351935
There's also a great introduction on mozilla developer network: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate
Alternative version, using
XPathEvaluator:function getElementByXPath(path) { return new XPathEvaluator() .createExpression(path) .evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE) .singleNodeValue } console.log( getElementByXPath("//html[1]/body[1]/div[1]") );<div>foo/bar</div>From Stack Overflow: asked by pMan, answered by yckart (CC BY-SA 4.0)
Difference between webdriver.Dispose(), .Close() and .Quit()
This is a good question I have seen people use Close() when they shouldn't. I looked in the source code for the Selenium Client & WebDriver C# Bindings and found the following.
webDriver.Close()- Close the browser window that the driver has focus ofwebDriver.Quit()- Calls Dispose()webDriver.Dispose()Closes all browser windows and safely ends the session
The code below will dispose the driver object, ends the session and closes all browsers opened during a test whether the test fails or passes.
public IWebDriver Driver; [SetUp] public void SetupTest() { Driver = WebDriverFactory.GetDriver(); } [TearDown] public void TearDown() { if (Driver != null) Driver.Quit(); }In summary ensure that Quit() or Dispose() is called before exiting the program, and don't use the Close() method unless you're sure of what you're doing.
Note
I found this question when try to figure out a related problem why my VM's were running out of harddrive space. Turns out an exception was causing Quit() or Dispose() to not be called every run which then caused the appData folder to fill the hard drive. So we were using the Quit() method correctly but the code was unreachable. Summary make sure all code paths will clean up your unmanaged objects by using exception safe patterns or implement IDisposableAlso
In the case of RemoteDriver calling Quit() or Dispose() will also close the session on the Selenium Server. If the session isn't closed the log files for that session remain in memory.From Stack Overflow: asked by Puran Joshi, answered by rcasady616 (CC BY-SA 3.0)
What would be an alternate to [TearDown] and [SetUp] in MSTest?
You would use
[TestCleanup]and[TestInitialize]respectively.From Stack Overflow: asked by Maya, answered by Tejs (CC BY-SA 3.0)
Can Selenium WebDriver open browser windows silently in the background?
If you are using Selenium web driver with Python, you can use PyVirtualDisplay, a Python wrapper for Xvfb and Xephyr.
PyVirtualDisplay needs Xvfb as a dependency. On Ubuntu, first install Xvfb:
sudo apt-get install xvfbThen install PyVirtualDisplay from PyPI:
pip install pyvirtualdisplaySample Selenium script in Python in a headless mode with PyVirtualDisplay:
#!/usr/bin/env python from pyvirtualdisplay import Display from selenium import webdriver display = Display(visible=0, size=(800, 600)) display.start() # Now Firefox will run in a virtual display. # You will not see the browser. browser = webdriver.Firefox() browser.get('http://www.google.com') print browser.title browser.quit() display.stop()EDIT
The initial answer was posted in 2014 and now we are at the cusp of 2018. Like everything else, browsers have also advanced. Chrome has a completely headless version now which eliminates the need to use any third-party libraries to hide the UI window. Sample code is as follows:
from selenium import webdriver from selenium.webdriver.chrome.options import Options CHROME_PATH = '/usr/bin/google-chrome' CHROMEDRIVER_PATH = '/usr/bin/chromedriver' WINDOW_SIZE = "1920,1080" chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE) chrome_options.binary_location = CHROME_PATH driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options ) driver.get("https://www.google.com") driver.get_screenshot_as_file("capture.png") driver.close()From Stack Overflow: asked by kevzettler, answered by Amistad (CC BY-SA 4.0)
Can Selenium interact with an existing browser session?
This is a pretty old feature request: Allow webdriver to attach to a running browser. So it's officially not supported.
However, there is some working code which claims to support this: https://web.archive.org/web/20171214043703/http://tarunlalwani.com/post/reusing-existing-browser-session-selenium-java/.
From Stack Overflow: asked by Angel Romero, answered by Robert Munteanu (CC BY-SA 4.0)
WebDriver click() vs JavaScript click()
Contrarily to what the currently accepted answer suggests, there's nothing specific to PhantomJS when it comes to the difference between having WebDriver do a click and doing it in JavaScript.
The Difference
The essential difference between the two methods is common to all browsers and can be explained pretty simply:
WebDriver: When WebDriver does the click, it attempts as best as it can to simulate what happens when a real user uses the browser. Suppose you have an element A which is a button that says "Click me" and an element B which is a
divelement which is transparent but has its dimensions andzIndexset so that it completely covers A. Then you tell WebDriver to click A. WebDriver will simulate the click so that B receives the click first. Why? Because B covers A, and if a user were to try to click on A, then B would get the event first. Whether or not A would eventually get the click event depends on how B handles the event. At any rate, the behavior with WebDriver in this case is the same as when a real user tries to click on A.JavaScript: Now, suppose you use JavaScript to do
A.click(). This method of clicking does not reproduce what really happens when the user tries to click A. JavaScript sends theclickevent directly to A, and B will not get any event.
Why a JavaScript Click Works When a WebDriver Click Does Not?
As I mentioned above WebDriver will try to simulate as best it can what happens when a real user is using a browser. The fact of the matter is that the DOM can contain elements that a user cannot interact with, and WebDriver won't allow you to click on these element. Besides the overlapping case I mentioned, this also entails that invisible elements cannot be clicked. A common case I see in Stack Overflow questions is someone who is trying to interact with a GUI element that already exists in the DOM but becomes visible only when some other element has been manipulated. This sometimes happens with dropdown menus: you have to first click on the button the brings up the dropdown before a menu item can be selected. If someone tries to click the menu item before the menu is visible, WebDriver will balk and say that the element cannot be manipulated. If the person then tries to do it with JavaScript, it will work because the event is delivered directly to the element, irrespective of visibility.
When Should You Use JavaScript for Clicking?
If you are using Selenium for testing an application, my answer to this question is "almost never". By and large, your Selenium test should reproduce what a user would do with the browser. Taking the example of the drop down menu: a test should click on the button that brings up the drop down first, and then click on the menu item. If there is a problem with the GUI because the button is invisible, or the button fails to show the menu items, or something similar, then your test will fail and you'll have detected the bug. If you use JavaScript to click around, you won't be able to detect these bugs through automated testing.
I say "almost never" because there may be exceptions where it makes sense to use JavaScript. They should be very rare, though.
If you are using Selenium for scraping sites, then it is not as critical to attempt to reproduce user behavior. So using JavaScript to bypass the GUI is less of an issue.
From Stack Overflow: asked by alecxe, answered by Louis (CC BY-SA 3.0)
Get HTML source of WebElement in Selenium WebDriver using Python
You can read the
innerHTMLattribute to get the source of the content of the element orouterHTMLfor the source with the current element.Python:
element.get_attribute('innerHTML')Java:
elem.getAttribute("innerHTML");C#:
element.GetAttribute("innerHTML");Ruby:
element.attribute("innerHTML")JavaScript:
element.getAttribute('innerHTML');PHP:
$element->getAttribute('innerHTML');It was tested and worked with the
ChromeDriver.From Stack Overflow: asked by Chris W., answered by Nerijus (CC BY-SA 4.0)
Selenium using Python - Geckodriver executable needs to be in PATH
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
Actually, the Selenium client bindings tries to locate the
geckodriverexecutable from the systemPATH. You will need to add the directory containing the executable to the system path.On Unix systems you can do the following to append it to your system’s search path, if you’re using a Bash-compatible shell:
export PATH=$PATH:/path/to/directory/of/executable/downloaded/in/previous/stepOn Windows you will need to update the Path system variable to add the full directory path to the executable geckodriver manually or command line** (don't forget to restart your system after adding executable geckodriver into system PATH to take effect)**. The principle is the same as on Unix.
Now you can run your code same as you're doing as below :-
from selenium import webdriver browser = webdriver.Firefox()selenium.common.exceptions.WebDriverException: Message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line
The exception clearly states you have installed Firefox some other location while Selenium is trying to find Firefox and launch from the default location, but it couldn't find it. You need to provide explicitly Firefox installed binary location to launch Firefox as below :-
from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary('path/to/installed firefox binary') browser = webdriver.Firefox(firefox_binary=binary)From Stack Overflow: asked by tadm123, answered by Saurabh Gaur (CC BY-SA 4.0)
How to take a screenshot with Selenium WebDriver?
Java
Yes, it is possible. The following example is in Java:
WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com/"); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // Now you can do whatever you need to do with it, for example copy somewhere FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));From Stack Overflow: asked by James Hollingworth, answered by Sergii Pozharov (CC BY-SA 3.0)
How do I find an element that contains specific text in Selenium WebDriver (Python)?
Try the following:
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")From Stack Overflow: asked by josh, answered by Ricky Sahu (CC BY-SA 3.0)
Headless Browser and scraping - solutions
If Ruby is your thing, you may also try:
- https://github.com/chriskite/anemone (dev stopped)
- https://github.com/sparklemotion/mechanize
- https://github.com/postmodern/spidr
- https://github.com/stewartmckee/cobweb
- http://watirwebdriver.com/ (Selenium)
also, Nokogiri gem can be used for scraping:
there is a dedicated book about how to utilise nokogiri for scraping by packt publishing
From Stack Overflow: asked by Inoperable, answered by rkj (CC BY-SA 3.0)
Wait until page is loaded with Selenium WebDriver for Python
The
webdriverwill wait for a page to load by default via.get()method.As you may be looking for some specific element as @user227215 said, you should use
WebDriverWaitto wait for an element located in your page:from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException browser = webdriver.Firefox() browser.get("url") delay = 3 # seconds try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement'))) print "Page is ready!" except TimeoutException: print "Loading took too much time!"I have used it for checking alerts. You can use any other type methods to find the locator.
EDIT 1:
I should mention that the
webdriverwill wait for a page to load by default. It does not wait for loading inside frames or for ajax requests. It means when you use.get('url'), your browser will wait until the page is completely loaded and then go to the next command in the code. But when you are posting an ajax request,webdriverdoes not wait and it's your responsibility to wait an appropriate amount of time for the page or a part of page to load; so there is a module namedexpected_conditions.From Stack Overflow: asked by apogne, answered by Zeinab Abbasimazar (CC BY-SA 3.0)
Typing the Enter/Return key in Selenium
import org.openqa.selenium.Keys WebElement.sendKeys(Keys.RETURN);The
importstatement is for Java. For other languages, it is maybe different. For example, in Python it isfrom selenium.webdriver.common.keys import KeysFrom Stack Overflow: asked by croixhaug, answered by Ralph (CC BY-SA 4.0)
How to select a drop-down menu value with Selenium using Python?
Selenium provides a convenient
Selectclass to work withselect -> optionconstructs:from selenium import webdriver from selenium.webdriver.support.ui import Select driver = webdriver.Firefox() driver.get('url') select = Select(driver.find_element_by_id('fruits01')) # select by visible text select.select_by_visible_text('Banana') # select by value select.select_by_value('1')See also:
From Stack Overflow: asked by Adam Bovien, answered by alecxe (CC BY-SA 4.0)
Wait for page load in Selenium
You can also check pageloaded using following code
IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00)); wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));From Stack Overflow: asked by karthick kumar, answered by Imran (CC BY-SA 3.0)
How can I scroll a web page using selenium webdriver in python?
You can use
driver.execute_script("window.scrollTo(0, Y)")where Y is the height (on a fullhd monitor it's 1080). (Thanks to @lukeis)
You can also use
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")to scroll to the bottom of the page.
If you want to scroll to a page with infinite loading, like social network ones, facebook etc. (thanks to @Cuong Tran)
SCROLL_PAUSE_TIME = 0.5 # Get scroll height last_height = driver.execute_script("return document.body.scrollHeight") while True: # Scroll down to bottom driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_heightanother method (thanks to Juanse) is, select an object and
label.sendKeys(Keys.PAGE_DOWN);From Stack Overflow: asked by user2523364, answered by OWADVL (CC BY-SA 4.0)
How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?
Chrome
This can be achieved by three different approaches (see my blog article here for more details):
- Search in
Elementspanel like below - Execute
$x()and$$()inConsolepanel, as shown in Lawrence's answer - Third party extensions (not really necessary in most of the cases, could be an overkill)
Here is how you search XPath in
Elementspanel:- Press F12 to open Chrome Developer Tool
- In "Elements" panel, press Ctrl+F
- In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.
Firefox (since version 75)
Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.
Firefox (prior version 75)
- Either select "Web Console" from the Web Developer submenu in the
Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
or press the Ctrl+Shift+K (Command+Option+K on OS X) keyboard shortcut. In the command line at the bottom use the following:
$(): Returns the first element that matches. Equivalent todocument.querySelector()or calls the$function in the page, if it exists.$$(): Returns an array of DOM nodes that match. This is like fordocument.querySelectorAll(), but returns an array instead of aNodeList.$x(): Evaluates an XPath expression and returns an array of matching nodes.
Firefox (prior version 49)
From Stack Overflow: asked by user3448242, answered by Yi Zeng (CC BY-SA 4.0)
- Search in
Scroll Element into View with Selenium
Have tried many things with respect to scroll, but the below code has provided better results.
This will scroll until the element is in view:
WebElement element = driver.findElement(By.id("id_of_element")); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element); Thread.sleep(500); //do anything you want with the elementFrom Stack Overflow: asked by Dan at Demand, answered by Amith (CC BY-SA 4.0)
How can I work with file uploads during a Webdriver test?
Uploading files using Webdriver
Note: this answer applies to Selenium 2. Apparently Selenium 3 changed the interface again.
Locally
If the file is on the same machine or a mapped network drive, this is actually really straightforward: You need to "type" the path to the file into the file upload control. Example:
driver = webdriver.Firefox() element = driver.find_element_by_id("fileUpload") element.send_keys("C:\myfile.txt")(Code from This SO answer)
Using RemoteWebDriver
In order to enable the transfer of the file from your local machine to the remote machine so it can be uploaded, you need to set what's called a File Detector. Java example:
driver.setFileDetector(new LocalFileDetector()); WebElement upload = driver.findElement(By.id("myfile")); upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg");(Code from, and more information located at, Sauce Labs)
From Software Quality Assurance & Testing Stack Exchange: asked by Yamikuronue, answered by Yamikuronue (CC BY-SA 4.0)
How do I close the browser window at the end of a Selenium test?
driver.close()anddriver.quit()are two different methods for closing the browser session in Selenium WebDriver.driver.close()- It closes the the browser window on which the focus is set.driver.quit()– It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.You should use
driver.quit()whenever you want to end the program. It will close all opened browser window and terminates the WebDriver session. If you do not usedriver.quit()at the end of program, WebDriver session will not close properly and files would not be cleared off memory. This may result in memory leak errors.From Software Quality Assurance & Testing Stack Exchange: asked by Aaron, answered by Sneha Singh (CC BY-SA 4.0)
How to avoid triggering google captcha while browsing in a selenium-driven browser?
By definition, resolving a CAPTCHA cannot be automated: Otherwise it could not tell computers and humans apart and hence fails being a CAPTCHA.
How to handle a CAPTCHA in a test environment:
- Use a service like http://www.deathbycaptcha.com which has an API to return the text of the CAPTCHA for you. Average response is 15 seconds with a result rate of 90% or so they say. Sounds like something to try.
- Google officially prevents automated integration testing of any platform using google oauth. If you're using a gsuite domain for your test accounts, however, you can run your own identity provider to handle the auth
- Ask your development team to remove the CAPTCHA field on the test environment.
- Ask your development team to make a sandbox like CAPTCHA, that will accept a single input text every time
- If your are using custom CAPTCHA module, you can ask developer to generate an API of CAPTCHA generation for testing environment.
- You can ask dev team to add CAPTCHA code as title in markup, then you can access this title and bypass the CAPTCHA, but only in the testing environment.
Generally if they've added a CAPTCHA to their site, they might have noticed spam attempts to login and such want to mitigate those. Contact the website administrator and mention to them what you've been doing and ask if they'd provide something for you so you can continue what you're doing.
From Software Quality Assurance & Testing Stack Exchange: asked by MxLDevs, answered by Brian McCarthy (CC BY-SA 3.0)
A way to match on text using CSS locators
css=a[text='Log Out'] or a[innertext='Log Out']Can you please try this one out?
Or if that doesn't work and you still don't want to use xpath because it's slow, you can always try:
link=Log Out. That's still better then xpath.EDIT:
So i found a possible solution for you mate. If you are trying to find an exact String you could always use Regular expression like this:
css=div:contains("^ab$")Just replace div with a and there you go. This will find ONLY AB in whatever text div it looks for. OFC if you have more then one links with text AB (which is a bad thing :P ) then it will find them all..
Try this and see if it helps. :)
From Software Quality Assurance & Testing Stack Exchange: asked by Brian O'Neill, answered by Hannibal (CC BY-SA 4.0)
Is adding IDs to everything standard practice when using Selenium?
It's not unusual. IDs tend to aid greatly in creating more stable UI tests, since class name changes or other refactoring is less likely to break tests. Also, dynamically populated lists tend to be high-maintenance in UI automation, and having predictable IDs can help with that. Using XPath is not only slow, as squeemish pointed out (and slowness itself can break tests if there are any timeouts, which leads those tests being fragile), but XPath also tends to be more vulnerable to UI changes, again increasing test maintenance.
Basically, your test engineers are probably finding that their test UI automation is fragile. This is a change from developers that can dramatically reduce test maintenance costs and, in turn, reduce the turn-around time on testing new builds. Fragility in UI tests is hard to manage, so other issues might also need to be resolved before you see the benefits of adding IDs.
From Software Quality Assurance & Testing Stack Exchange: asked by ejunker, answered by Ethel Evans (CC BY-SA 3.0)
How to make selenium tests more stable?
I have struggled with this issue in several companies. It always seems to come up at some point and then be a major issue over time.
I too have walked the path of sleeps, polling waits, check for ajax done, check for js done, check for animations done, etc. They sometimes help with some of the errors but it always seems that just when you think you have fixed something and a bunch of runs have passed then wham! Most frustrating of all, when you run the spec yourself it always seems to pass the 2nd time.
My approach to this now is: re-run the example
Again, before resorting to this I put a lot of work into diagnosing the issue and trying various approaches. When various approaches have failed I will consider adding a fixed sleep of 1 to 2 seconds (before polling, i.e. issuing find element commands). If this doesn't help I go for the retry example route.
I am able able to do this easily this with the ruby-rspec-capybara implementation of WebDriver plus use of the rspec-retry gem.
Basically when I've identified one of those intermittent types of errors that I have not been able to resolve, I allow the retry approach to address it.
Initially I only did this for the well known ruby
Net::ReadTimeouterror. More recently expanded my use toCapybara::ElementNotFoundand this is working well.The main downside is that during test automation development you may wish to disable this so that real element not found situation error out immediately.
This approach is also clearly not ideal and it not favored by some developers. I believe it is a 'real world' compromise and is a good approach given the following caveats:
- The spec usually passes
- The failure rate is low, e.g. 2-5%
- The spec usually passes on re-try
- More specific approaches such as polling waits or ajax waits haven't addressed the issue
- You limit the number of re-tries
- You scope the errors to re-try - this is important, for example I use the array
[Net::ReadTimeout, Capybara::ElementNotFound]to limit what gets re-tried.
From Software Quality Assurance & Testing Stack Exchange: asked by Alex, answered by Michael Durrant (CC BY-SA 4.0)
Page Objects design issues
I find the Page Object pattern very useful, and use a modified PageFactory (parameterized for custom timeouts).
I also use WidgetObjects (basically, PageObjects with a parent reference via constructor) to represent common themes across pages.
I don't think URL association is necessary on all pages, so I keep it out of my base class. URL params? I keep my PageObjects user-centric; if the user doesn't need to know, the PageObject doesn't either. Object state is a product of sequential executions and constructions, only.
format(:Date): Stringselect(:WebElement, :String)selectMany(:WebElement, :int)selectRadio(:WebElement, ...)- ....
I also have many Predicates, Functions, and ExpectedConditions defined in a singleton utility class, which are used with FluentWait to implement:
waitToBeAt(path:String, timeout:int)varEquals(var:String, value:String, timeout:int)switchToWindow(path:String, value:String, timeout:int): WebDriverwindowIsClosed(winTitle:String, timeout:int)elementLocated(:By, timeout:int): WebElement- ....
- I also keep JavaScript snippets in discrete files and at startup, read them into a Map, indexed by the filename. This is infinitely more maintainable than writing escaped source within source.
- I usually use my custom PageFactory to initialize, or for complex objects I call the constructor and pass the instance to PageFactory for static element initialization.
- My PageObjects always know how to navigate to the next page, and have methods returning those PageObjects. I use chaining (
return this;) wherever possible because it makes the test code extremely fluent, which is my favorite part about using this pattern:
/** * Test Utility. Create an Assembly. * @return A reference to the viewport of the created Assembly. */ public ViewAssemblyPage createAssembly(String title, String type, String description, Date dueDate, int numParts) { AssemblyPage assy = login("JoeCoder", "foopass") .createRecord() .assembly(type) .formInput(title, description, dueDate); return assy.getTable() .openPartsPicker() .findParts(type) .selectSomeParts(numParts) .submitSelection(); }From Software Quality Assurance & Testing Stack Exchange: asked by Sassy, answered by Joe Coder (CC BY-SA 3.0)
Under what circumstances is Sikuli better for test automation than Selenium or Watir?
I can come up with some ideas:
You are testing for devs who don't know how to give their elements IDs or use other APIs, and won't go back and fix things in a timely fashion. This is accumulating technical debt - better to get the devs to do it right - but, e.g., on legacy apps designed without a thought toward testability, screenshot testing might be the only reasonable option for creating UI tests. In fact, this tool might solve an upcoming problem for me along those lines . . .
You are testing specifically to make sure that the UI stays reasonably similar in appearance. Normal UI testing doesn't care what the button looks like, and couldn't catch if the image used got deleted by accident or swapped with an old button image. I've seen other screenshot testing used for these purposes on major apps.
If you can get really accurate screenshots from the PM, you could make your UI tests before the IDs have been assigned to the elements and also ensure that the final UI matches PM specs, automatically.
As long as you can assign screenshots to variables and reuse them (so you only have one screenshot of the "Okay" button in the entire test suite), maintenance wouldn't be too bad IMO. It might even be easier if IDs are still changing and the UI is in extreme flux. I worked on a project once where devs kept removing IDs by accident, and I had to wait literally weeks before I got a reliable identifier quite regularly. But UI elements will always have an image, by definition, meaning a 1-minute test fix rather than a 3-week wait where I can't run that test automatically and need to run it manually, or a 15-minute to 1-hour fix to code a work-around function and test it.
The main difficulty I can think of would arise when there could be two or more similar pieces of UI (e.g., two "Okay" buttons, one on an error and one on a standard configuration screen), but even IDs can have similar issues (do you want "dynamicMenuOption11" or "dynamicMenuOption12"?), and you could probably fix this most of the time just by taking a bigger screenshot (e.g., get the edge of the "Apply" button or error dialogue to identify the right button). That's an easier fix than coding the ID in, checking other values, and so on, IMO.
Edit: I do think Tarun brings up a good point about how well Sikuli tolerates changes. The video claims some sort of "best-fit" matching, but how tolerant is that? And, if it is too tolerant, could it produce false actions and false passes?
From Software Quality Assurance & Testing Stack Exchange: asked by user246, answered by Ethel Evans (CC BY-SA 3.0)
Running WebDriver without opening actual browser window
One option is HTMLUnit, which is headless but has its own proprietary JavaScript rendering engine, so it is possible that it will behave differently than existing browsers (If you do use HTMLUnit, don't forget to enable JavaScript when you instantiate it).
The second option is to use XVFB; this will run the tests in a virtual frame buffer environemt. This has been reported quite a few times on the Selenium users mailing list as well as the Selenium blog, see this post for some XVFB implementations.
Linking directly to the tutorials:
If you google for Selenium and XVFB you'll find lots more info.
From Software Quality Assurance & Testing Stack Exchange: asked by JustBeingHelpful, answered by Ardesco (CC BY-SA 3.0)
How to handle dynamic changing ID's In XPath?
At this situation, We have lots of options-
Option 1: Look for any other attribute which Is not changing every time In that div node like name, class etc. So If this div node has class attribute then we can write xpath as bellow.
//div[@class='post-body entry-content']/div[1]/form[1]/input[1]Option 2: We can use absolute xpath (full xpath) where you do not need to give any attribute names In xpath.
/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[2]/div[1]/form[1]/input[1]Option 3: We can use starts-with function. In this xpath's ID attribute, "post-body-" part remains same every time.
//div[starts-with(@id,'post-body-')]/div[1]/form[1]/input[1]Option 4: We can use contains function. Same way you can use contains function as bellow.
div[contains(@id,'post-body-')]/div[1]/form[1]/input[1]From Software Quality Assurance & Testing Stack Exchange: asked by Bharat Mane, answered by Bharat Mane (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA19 questions
- Software Quality Assurance & Testing Stack Exchangeby its contributors, named on each answerCC BY-SA10 questions