How to write my own customize locator for Selenium webdriver in java? How to write my own customize locator for Selenium webdriver in java? selenium selenium

How to write my own customize locator for Selenium webdriver in java?


using c#

using OpenQA.Selenium;using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Linq;using System.Text;using System.Threading.Tasks;public class ImageBy : By{    public ImageBy(string imageByString)    {        FindElementMethod = (ISearchContext context) =>        {            IWebElement mockElement = context.FindElement(By.XPath("//img[@src='" + imageByString + "']"));            return mockElement;        };        FindElementsMethod = (ISearchContext context) =>        {            ReadOnlyCollection<IWebElement> mockElements = context.FindElements(By.XPath("//img[@src='" + imageByString + "']"));            return mockElements;        };    }}

and the usage would be as follows

[FindsBy(How = How.Custom, Using = @"/path/to/img", CustomFinderType = typeof(ImageBy) )]private IWebElement MenuStartButton = null;

Using Java

import java.util.List;import org.openqa.selenium.By;import org.openqa.selenium.SearchContext;import org.openqa.selenium.WebElement;public class ByImageSrc extends By {    private final String imageByString;    public ByImageSrc(String imageByString)    {        this.imageByString = imageByString;    }    @Override    public List<WebElement> findElements(SearchContext context)     {         List<WebElement> mockElements = context.findElements(By.xpath("//img[@src='" + imageByString + "']"));         return mockElements;    }}

usage :

WebElement element = driver.findElement(new ByImageSrc("/path/to/image"));


You would need to subclass the By class and provide an implementation for findElement and findElements methods, since this is where the 'meat' of the actual element finding occurs.

You should then be able to use it with the normal driver.FindElement then.


I know this doesn't really answer your question, but why not just use Xpath?It seems like it would be a lot of extra work to build out a new locator instead of just crawling the DOM.

For example: driver.findElement(By.Xpath("//div[@username='YourUsername']")

I could give a better example with some more detail about the attribute and page you're working with.