0% found this document useful (0 votes)
120 views

Selenium Cheatsheet

The document provides guidance on locating elements in Selenium using XPath and CSS selectors. It discusses: - Preferring XPath and CSS over IDs or names due to their variability - Common CSS selector syntax like using classes, attributes, descendant combinators - Using pseudo-classes like :first-child,:last-child and nth-child() - Tips for dealing with class names containing spaces - Checking element counts and taking screenshots in Selenium - Using waits like implicit, explicit and fluent waits for synchronization - Identifying broken links by checking the HTTP response code

Uploaded by

AdityaAgarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Selenium Cheatsheet

The document provides guidance on locating elements in Selenium using XPath and CSS selectors. It discusses: - Preferring XPath and CSS over IDs or names due to their variability - Common CSS selector syntax like using classes, attributes, descendant combinators - Using pseudo-classes like :first-child,:last-child and nth-child() - Tips for dealing with class names containing spaces - Checking element counts and taking screenshots in Selenium - Using waits like implicit, explicit and fluent waits for synchronization - Identifying broken links by checking the HTTP response code

Uploaded by

AdityaAgarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Evey object may not have ID, className or name- Xpath and CSS Preferred

Alpha numeric id may vary on every refresh- check


Confirm the link object with anchor "a" tag
Classes should not have spaces- Compound classes cannot be accepted
Multipl values - Selenium identifies the first one- Scans from top left
Double quotes inside double quotes are not accepted
Xpath/CSS can be defined in n number of ways
Rightclick copy on blue highlighted html code to generate xpath
Firepath depreciated from firefox-
when xpath starts with html-Not reliable- Switch browser to get another one
There is no direct way to get CSS in chrome. You will find it in tool bar
Degrade browser to less firefox 55 to ge Firepath
Chropath and SelectorsHub are two common chrome extensions for verfying locators
$("") - for css , $x("") or xpath in the console. Or after hitting f12, hit ctrl+f to get a search box for xpaths and css directly
//tagName[@attribute='value'] - xpath syntax
tagName[attribute='value'] -CSS tagName#id- CSS tagname.classname- CSS
CSS selectors with multiple attributes :
-> input#id_value[placeholder='somevalue'][name='somename']
-> input.classname[placeholder='somevalue'][name='somename']

CSS selectors for substring matches :


-> input[name^='myName'] : match prefix of the text
-> input[name$='myName'] : match suffix of the text
-> input[name*='myName'] : match subsubtring of the text(contains the string or not)

Css selectors for direct child of an element : (> symbol)


div#id_name > div[name='divnamevalue']

CSS selector for selecting all childs of an element : (descendent combinator i.e. space character)
div#idname div[class='newclassname'] : selects all the child of the parent element

CSS selector to select the next sibiling : (+ operator : adjacent sibling combinator)
tagname1[attributename='attributevalue']+tagname2[attributename='attributeValue']
the tagname2 is only selected if it is immediately follows (immediate sibling) of tagname1 and both are the childs of the same
CSS Psedu classes
It is a keyword added to the CSS selector that specified the special state of the weblement.
1. first-child : returns first element from a group of siblings
tagname[attributename='attributeValue']>:first-child or tagname[attributename='attributeValue'] :first-child
2. last-child : returns last element from a group of siblings
tagname[attributename='attributeValue']>:last-child
3. nth-child() : returns nth child element from a group of siblings counting from first element
tagname[attributename='attributeValue']>:nth-child(3)
4. nth-last-child() : returns nth element from a group of siblings counting from the last element
tagname[attributename='attributeValue']>:nth-last-child(4)
ex -> >:first-child or :first-child or tagname:first-child or *:nth-child

5. first-of-type
tagname1[attributename='attributeValue']>tagname2:first-of-type -> will select first child of type tagname2 under the paren
6. last-of-type
tagname1[attributename='attributeValue']>tagname2:last-of-type ->will select last child of type tagname2 under the parent t
7.nth-of-type()
tagname1[attributename='attributeValue']>tagname2:nth-of-type ->will select last child of type tagname2 under the parent ta

//tagName[contains(@attribute,'value')] - xpath regular expression


//tagName[text()='value'] or //tagName[contains[text(),'value']];
tagName[Atrribute*='value'] - Css regular expression ("*" to search for any attribute containing that value after assignment op
hwo to get elemts with class names having spaces :
1. cssSelector(“div[class=’agb thm tc’]”)
2.cssSelector(“div.agb.thm.tc”); or cssSelector(“.agb.thm.tc”);
3.xpath(“//div[@class=’’agb thm tc’]”);
4.xpath(“//div[contains(@class, ‘thm’) and contains(@class, ‘agb’)]”);

driver.getElements().size : give the total number of elements found


driver.manage().window().maximize() : maximize the current browser window
driver.manage().window().deleteAllCookies() : deletes all cookies in the browser
org.tentng.assert : contains assertion validations : Asset.assertTrue (check if the condition is true),Assert.assertFalse(),Assert.a
driver.switchTo().alert() : switchs selenium context to look for any alerts already open
driver.switchTo().alert().accept() : accepts/Oks any browser alert popup that is open
driver.switchTo().alert().dimss() : cancels/no on any browser alert popup that is open(negative action on the popup). Howver,
present, i.e. cancel or no button is mot there then dismiss() works as accept().
Taking screenshots in selenium :
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //cast driver object into TakesScreenshot class and s
FileUtils.copyFile(src,new File("C:\\Users\\aditya\\screenshot.png")); //using fileutils create a new file in the local to actually

format code in eclipse : ctrl+shift+f


naming conventions : camelcase : class name stars with caps, and variable and methods with small letters ut multiple words, fi
eclipse debugging :
1. right click on line number to add/remove breakpoints
2. F6 : step over-> go to next line
3. Resume-> go to next breakpoint if any or continue execution
4. F5 : step into-> go inside the mthod called in the line

Selenium waits for synchronization


Implicit wait,expilicit wait,fluent wait and thread sleep
1. Implicit : defining wait time globally for the testcase-> telling selenium that if it doesn't find any element, then wait for n sec
throwing an exception. Advantage-> if i spedificy 5 sec as implicit wait, but element is available after 3 seconds then script con
whole 5 secs as it continuously reasons the DOMof the html page for the element.
syntax : driver.manage().timeouts().implicitlyWait(4,TimeUnit.SECONDS)

2. Explicit : to define wait for a particular element. used when an exclusive wait time is needed for any specific elements but n
WebDriverWait w = new WebDriverWait(driver, 5);
w.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//span[@class='promoInfo']")));

3. Fluent : to define wait for an element with regular polling. IT is a type of explicit wait. Explicit wait is of two type :
a) WebDriverWait ; - continuously checks the dom for the element till the element is found.(approx- every milisecond)
b) Fluent wait :- checks the dom for the element after regular intervals(polling) till timeout or till object is found. Unlike, webd
to build customized wait methods based on condition. both WebDriverWait and FluentWait implement Wait interface

sample code snippet :


Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(3))
.ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function <WebDriver,WebElement> () {

public WebElement apply(WebDriver driver) {


if(driver.findElement(By.cssSelector("div[id='finish'] h4")).isDisplayed())
return driver.findElement(By.cssSelector("div[id='finish'] h4"));
else
return null;
}

});

scope of selenium Webdriver object can be limited by making a webelement and calling the driver methods on the element. F
driver.findElements(By.xpath("//a")).size() //will give the no of links on the entire page.

WebElement footer = driver.findElement(By.xpath("//div[@class=' footer_top_agile_w3ls gffoot footer_style']"));


footer.findElements(By.xpath("//a")).size()) //this only gives the number of links in the footer element taken above. Hence, th
method is reduced. this optimizes the script.

To Create a combination of keyboard key presses in selenium without actions class :


String openLinkInNewTab = Keys.chord (Keys.CONTROL,Keys.ENTER);
driver.findElement(By.id("divmyName")).sendKeys(openLinkInNewTab); //here in the sendkeys method we pass the key comb
Identifying broken links using java URLs class :
broken links on webpages indicate the URL attached to the link is not working or that Url has no page attached to it. if the stat
something closer to that then it is working but if the response code is 400 and above then the link is having some iissue/broke

String url = driver.findElement(By.id(URLidname")).getAttribute("href");


HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection(); //creating a java url connection object
conn.setRequestMethod("HEAD");
conn.connect(); //to connect to the URL
int URLstatuscode = conn.getResponseCode(); //to get the response code

using Assert.assertTrue or similar Assert class methods, stops the test then and there. So instead, SoftAssert class can be used
failures and then at the end fail the test by showing all the errors
SoftAssert a =new SoftAssert();
a.AssertTrue(i<0,"i should be less than zero");
a.assertAll(); // to be used after all assertions to throw the assertion errors.

You might also like