Dark Star1
Dark Star1

Reputation: 7413

Is it possible to locate element by partial id match in Selenium

I am trying to locate elements with generated ids wherein some part of the ID is known; for example:

id="page_x002e_x0023_default-create-firstname"

in which the last 3 words (_default-create-firstname) are known but anything preceding that is subject to change. Is this possible?

Upvotes: 53

Views: 114776

Answers (6)

Suntje
Suntje

Reputation: 21

I use: a[id*='example']

when my ID is something like example_12

Upvotes: 0

Vikki
Vikki

Reputation: 2025

Work one

driver.find_element_by_xpath("//*[contains(@id, 'jobs-search-box-keyword-id')]")

Not work ones, all got the same error, TypeError: 'str' object is not callable

1. driver.find_element(By.XPATH("//*[contains(@id, 'jobs-search-box-keyword-id')]")).text

2. driver.find_element(By.XPATH("//*[contains(@id, 'jobs-search-box-keyword-id')]").text).text

3. driver.find_element(By.XPATH("//*[contains(@id, 'jobs-search-box-keyword-id')]")).get_attribute("innerHTML")

4. driver.find_element(By.XPATH("//*[contains(@id, 'jobs-search-box-keyword-id')]").get_attribute("innerHTML")).get_attribute("innerHTML")

I use python 3.7.6, selenium 3.141.0

Upvotes: 1

alecxe
alecxe

Reputation: 474191

You can apply an ends-with CSS selector:

By.cssSelector("[id$=default-create-firstname]")

Update

Some time went by since the answer was posted. Here some update from the linked mozilla developer page and comments below:

New use By.css instead of By.cssSelector

By.css("[id$=default-create-firstname]")

Also see the four possibilities of

  • beginning with
  • anywhere inside
  • anywhere inside regardless capitalization
  • end with

/* Internal links, beginning with "#" */
a[href^="#"] {
  background-color: gold;
}

/* Links with "example" anywhere in the URL */
a[href*="example"] {
  background-color: silver;
}

/* Links with "insensitive" anywhere in the URL,
   regardless of capitalization */
a[href*="insensitive" i] {
  color: cyan;
}

/* Links that end in ".org" */
a[href$=".org"] {
  color: red;
}

Upvotes: 72

Hari kishen
Hari kishen

Reputation: 483

You can try out this in Java-Selenium: you can use either ends-with() or contains(). I think Both should work.

driver.findElement(By.xpath("//*[ends-with(@id,'_default-create-firstname')]"));
driver.findElement(By.xpath("//*[contains(@id, '_default-create-firstname')]"));

Upvotes: 23

Jorge
Jorge

Reputation: 358

This works with selenium vba

 .FindElementsByXPath( "//*[contains(@class, 'unique-string')]" )

Upvotes: 6

Cathal
Cathal

Reputation: 1338

If you want to go down the xpath route then you could use contains(), like this:

//*[contains(@id,'_default-create-firstname')]

This will search the entire page for an id that contains the text "_default-create-firstname". It can be easily made more specific

Upvotes: 37

Related Questions