0

I have been using

WebElement strecord = driver.findElement(By.name("Ui_u123));

Value can only be located using "By.name"

Field is now dynamic but the first 3 characters are always "Ui_u"

How can i find it now , "By.name" contains ....?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Mark H
  • 91
  • 9

3 Answers3

0

You can try this xpath:

//*[starts-with(@name,'Ui_u')]  

Though this is xpath. I am not sure about starts-with with Name attribute.

It might match with more than one element. In that case you will have to use findElements()

Code :

List<WebElement> strecord = driver.findElements(By.xpath("//*[starts-with(@name,'Ui_u')]"));  

As a addition to @HellPine answers. You can write css selector as :

tagName[name^='Ui_u']
cruisepandey
  • 28,520
  • 6
  • 20
  • 38
0

Why don´t you try the CSS way [name*='Ui_u'] ?

Note the *= means contains and you can use [] for any tag on element.

Regards,

cruisepandey
  • 28,520
  • 6
  • 20
  • 38
HellPine
  • 21
  • 2
0

Answering straight, No, you can't use contains in conjunction with By.name.

Explaination

As per the Locator Strategies when you use driver.findElement(By.name("Ui_u123)); the internal Java Client implementation:

case "name":
  toReturn.put("using", "css selector");
  toReturn.put("value", "*[name='" + value + "']");
  break;

converts the locator strategy:

driver.findElement(By.name("Ui_u123));

to:

driver.findElement(By.cssSelector("[name='Ui_u123']));

You can find a detailed discussion in Official locator strategies for the webdriver


Now, if you forcefully try to use the keyword contains, it would raise InvalidSelectorException as follows:

org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression

If you want to implement an approach similar to contains you can use either of the following solutions:

  • ^ : To indicate an attribute value starts with

    WebElement strecord = driver.findElement(By.cssSelector("[name^='Ui_u']));
    
  • $ : To indicate an attribute value ends with (not applicable in your case as the attribute starts with Ui_u )

    WebElement strecord = driver.findElement(By.cssSelector("[name$='123']));
    
  • * : To indicate an attribute value contains

    WebElement strecord = driver.findElement(By.cssSelector("[name*='Ui_u']));
    

You can find a detailed discussion in How to get selectors with dynamic part inside using Selenium with Python?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352