Reputation:
Given this html:
<input id="test" value="my text" />
it is easy to get a handle on the input element with xpath. Something like:
input[@value="my text"]
But what if the original html looks like this:
<input id="test" />
It still has 'my text' in it if you look in the browser - because this has been added with javascript like this:
document.getElementById('test').value = 'my text';
In the fiddle you can see that the input field has the word(s) 'my text' in it but does not have a value attribute: https://jsfiddle.net/justinwyllie/5dsxa8mc/
How can I select this element? Just xpath - no jQuery.
Upvotes: 2
Views: 2613
Reputation: 473893
Taking into account that this is Python+Selenium, I would approach it the following way:
inputs = driver.find_elements_by_tag_name("input") # TODO: improve the locator to get less input elements
input_elm = next(input_elm for input_elm in inputs
if input.get_attribute("value") == "my text")
Note that get_attribute("value")
would get the computed value of the .value
property which is exactly why this would solve the problem.
Also note that next()
would throw you the StopIteration
exception if there would be no match - you can either handle that via try/except
, or provide a default value:
input_elm = next((input_elm for input_elm in inputs
if input.get_attribute("value") == "my text"), None)
Upvotes: 4