Reputation: 7413
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
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
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
/* 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
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
Reputation: 358
This works with selenium vba
.FindElementsByXPath( "//*[contains(@class, 'unique-string')]" )
Upvotes: 6
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