I have tried a few things such as this:
IWebDriver driver = new ChromeDriver(#"D:\Selenium");
driver.Navigate().GoToUrl("http://www.bladibla.com");
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("a"));
foreach (IWebElement element in elements)
{
if (element.Text.Equals("Bla"))
{
}
Console.WriteLine(element.Text);
}
Including some XPath without success. All I want is click the link represented by this html:
<img src="images/download16.png" alt="Download XYZ" />Bla
Any help would be very much appreciated. Thanks.
PS:
Current code:
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace Selenium
{
class Program
{
static void Main(string[] args)
{
try
{
IWebDriver driver = new ChromeDriver(#"D:\Selenium");
driver.Navigate().GoToUrl("http://www.doogal.co.uk/UKPostcodes.php?Search=AB1");
var test = driver.FindElement(By.CssSelector("a[href^='UKPostcodesKML']"));
driver.Close();
}
catch (Exception e)
{
throw;
}
}
}
}
You can use partial link text like below.
driver.findElement(By.partialLinkText("Bla"))
or
if the href is unique for that anchor, then you can get that specific anchor by using css selector like below.
driver.FindElement(By.CssSelector("a[href=xyz/bla.txt]")
This should work for you:
driver.findElement(By.xpath("//a[contains(text(), 'KML format')]")).click();
Or this:
driver.findElement(By.partialLinkText("KML format")).click();
Related
I am new to the Selenium .
I need to check the availability of a button in the system and need to mark it pass and fail with AssertEquals.
Please help me .
#Test
public void sellercheck () throws InterruptedException
{
Thread.sleep(2000);
driver.findElement(By.id("UserEvent")).click();
//String r=Read.getvalue().get(0);
//select the seller
driver.findElement(By.id("LegacyNumberCriterion")).sendKeys("123456");
driver.findElement(By.id("SuperUse")).click();
System.out.println("seller number entered");
try
{
if(driver.findElements(By.id("OrganizationBranchId")).size()!=0)
{
driver.findElement(By.id("button1")).click();
}
else
{
System.out.println("The button is not available for the seller");
}
}
catch(NoSuchElementException e)
{
System.out.println("Element does not exist!");
}
}
You can choose from following 2 solutions which suitable to you:
1] Code to check element present or not using assertion in Selenium Webdriver would be something like this:
assertTrue(!isElementPresent(By.id("id of button")));
2] This assertion verifies that there are no matching elements in the DOM and returns the value of Zero, so the assertion passes when the element is not present. Also it would fail if it was present.
Assert.assertEquals(0, driver.findElement(By.id("id of button")).size());
Try this solution and let me know if it works.
Try this piece of code with some simple tweaks to your own code:
WebDriver driver;
#Test
public void sellercheck () throws InterruptedException
{
Thread.sleep(2000);
driver.findElement(By.id("UserEvent")).click();
//String r=Read.getvalue().get(0);
//select the seller
driver.findElement(By.id("LegacyNumberCriterion")).sendKeys("123456");
driver.findElement(By.id("SuperUse")).click();
System.out.println("seller number entered");
try
{
if(driver.findElements(By.id("OrganizationBranchId")).size()!=0)
{
driver.findElement(By.id("button1")).click();
}
else
{
System.out.println("The button is not available for the seller");
}
}catch(NoSuchElementException e)
{
System.out.println("Element does not exist!");
}
}
Let me know if this works for you or update me the error you see.
Here i'm getting all checkboxes of a page but unable to select all check boxes when i tried below code its giving error.Here is my code
public class AllCheckBoxes {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.flipkart.com/mobiles/pr?p%5B%5D=facets.brand%255B%255D%3DSamsung&sid=tyy,4io&otracker=nmenu_sub_electronics_0_Samsung");
Thread.sleep(1000);
try {
// Option 1
List<WebElement> CHECKBOXlist = driver.findElements(By.xpath("//input[#type='checkbox']"));
// Option 2
//List<WebElement> CHECKBOXlist = driver.findElements(By.cssSelector("[type='checkbox']"));
System.out.println("Total Check Boxes are avaliable here are: "+CHECKBOXlist.size());
for (WebElement checkbox : CHECKBOXlist) {
checkbox.click();
}
} catch (Exception e) {
System.out.println(e.getMessage());
// Error as: Element is no longer attached to the DOM
// For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
}
driver.quit();
}
}
Can anybody guide me how to do this?
A stale element exception usually occurs when you are trying to interact with a web element from a previous page instance. Perhaps one of these checkboxes you are ticking does something like reload the page, if this is the case, then the remaining checkboxes to click will fail.
Edit: Yes this does seem to be the case after visiting the webpage you are trying to use in your code. My suggestion would be to use indexing within an XPath to get the checkboxes one at a time:
public class AllCheckBoxes {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.flipkart.com/mobiles/pr?p%5B%5D=facets.brand%255B%255D%3DSamsung&sid=tyy,4io&otracker=nmenu_sub_electronics_0_Samsung");
Thread.sleep(1000);
try {
// Option 1
List<WebElement> CHECKBOXlist = driver.findElements(By.xpath("//input[#type='checkbox']"));
// Option 2
//List<WebElement> CHECKBOXlist = driver.findElements(By.cssSelector("[type='checkbox']"));
System.out.println("Total Check Boxes are avaliable here are: "+CHECKBOXlist.size());
// this for loop will account for page loads:
for (int i = 0; i < CHECKBOXlist.size(); i++) {
driver.findElement(By.xpath("(//input[#type='checkbox'])[" + (i+1) + "]")).click();
}
} catch (Exception e) {
System.out.println(e.getMessage());
// Error as: Element is no longer attached to the DOM
// For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
}
driver.quit();
}
}
So basically, you're going to have to find the checkboxes individually rather than all at once to account for page reloading.
I have developed a s keyword driven framework. It has a action keyword to switch the frame.
It works fine with Mozilla. But when it comes to IE it is not switching. It logs error.
IE driver -IEDriverServer_x64_2.44.0
IE version -9
Selenium version -selenium-java-2.44.0
Thanks in advance.
public static void switchFrame(String object,String data)throws Exception{
try{
driver.switchTo().frame("Ifrm");
Log.info("Switched the frame");
}
catch(Exception e){
Log.error("Not able to switch the frame--- " + e.getMessage());
DriverScript.bResult = false;
}
}
Here exception occurs.
I assume, the value you specified in frame is id/name/etc. You have to access the frame by calling the driver with specified value. Code would be
driver.switchTo().frame(driver.findElement(By.id("Ifrm")));
Selenium won't let me switch to the iframe by ID on Internet Explorer, but it does allow me to switch by index. If you have some sort of property that you can check that it is only available on the iframe you can do the following
new WebDriverWait(driver, 5).until(
new Predicate<WebDriver>() {
#Override
public boolean apply(WebDriver input) {
try {
int i = 1;
while (true) {
driver.switchTo().defaultContent();
driver.switchTo().frame(i);
String aClass =
driver.findElement(By.xpath("/html/body"))
.getAttribute("class");
if (aClass.contains("modal")) {
return true;
}
++i;
}
} catch (NoSuchFrameException e) {
return false;
}
}
}
);
In my case I was looking for a body class of modal
Hi can anyone pls solve this. When i write a code to automate sometimes the elements are not identified and sometimes its not found even they are present, means even if the id is present it says element not found error. So I a trying to create a method where i would pass all the dom objects i find like Ex :
public static void Click(WebDriver driver, String name,Sting linktext,Sting id,Sting Xpath,String css)
{
driver.findElement(new ByAll(By.name(name),
By.linkText(linktext),
By.id(id),
By.xpath(xpath),
By.cssSelector(css))).click();
}
And i would pass what ever value i find in source page like sometimes it will have oly id or it ll have oly link text Ex:(when i import this method in other class)
Click(Webdriver driver, "username",null,"","//[fas].user");
is this the correct way to pass the arguments. can i pass like null and "" (blank). Pls help this would become a one simple effective framework for me.
you can use this 2 methods
public static WebElement findElement(WebDriver driver, By selector, long timeOutInSeconds) {
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.presenceOfElementLocated(selector));
return findElement(driver, selector);
}
public static WebElement findElementSafe(WebDriver driver, By selector, long timeOutInSeconds) {
try {
return findElement(driver, selector, timeOutInSeconds);
} catch (TimeoutException e) {
return null;
}
}
public static void waitForElementToAppear(WebDriver driver, By selector, long timeOutInSeconds, String timeOutMessage) {
try {
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(selector));
} catch (TimeoutException e) {
throw new IllegalStateException(timeOutMessage);
}
}
----------------
public static void click(WebDriver driver , By ... selector ){
for (By byPath : selector) {
WebElement element = findElementSafe(driver, byPath, 1);
if(element != null){
element.click();
}
}
}
I am trying to take a screenshot for failure methods and also want to put the same in my Report, I am able to take the screenshot but unable to show the same in HTML report. Following is my code, friends any clue on this ?
public class SB1 {
private static Logger logger = Logger.getLogger(SB1.class);
WebDriver driver = new FirefoxDriver();
#Test
public void Testone() {
driver.get("http://www.google.com/");
assert false;
}
public void catchExceptions(ITestResult result) {
System.out.println("result" + result);
String methodName = result.getName();
System.out.println(methodName);
if (!result.isSuccess()) {
try {
String failureImageFileName = new SimpleDateFormat("MM-dd-yyyy_HH-ss").format(new GregorianCalendar().getTime())+ ".png";
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(failureImageFileName));
String userDirector = System.getProperty("user.dir") + "/";
Reporter.log("<a href=\""+ userDirector + failureImageFileName +"\"><img src=\"file:///" + userDirector
+ failureImageFileName + "\" alt=\"\""+ "height='100' width='100'/> "+"<br />");
Reporter.setCurrentTestResult(null);
} catch (IOException e1) {
e1.printStackTrace();
}
}
Have you set ESCAPE_PROPERTY to false? This is what you will have to do if you want reportng to post the screenshot -
private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
and in your setUp-
System.setProperty(ESCAPE_PROPERTY, "false");
I tried this. It seems like if you set the System Property to false, it removes the escaping from the ENTIRE log... From what I can tell, the report is generated after the test, with whatever the system property is set to at the time. I want to insert the screenshot (which worked with above code) but I do not want to remove the other formatting (br tags).
You can use following code.
Reporter.log("<br>Chrome driver launched for ClassOne</br>");
Or you can use customize method, where you do not need to append the br tag everytime, use following customized method.
public void customLogReport(String testCaseDescription) throws Exception{
try{
Reporter.log("<br>" + testCaseDescription + "</br>");
}catch(Exception e){
e.printStackTrace();
}
}