Reputation: 363
How do I locate an input field via its label using webdriver?
I like to test a certain web form which unfortunately uses dynamically generated ids, so they're unsuitable as identifiers.
Yet, the labels associated with each web element strike me as suitable. Unfortunately I was not able to do it with the few suggestions offered on the web. There is one thread here at SO, but which did not yield an accepted answer:
Selenium WebDriver Java - Clicking on element by label not working on certain labels
To solve this problem in Java, it is commonly suggested to locate the label as an anchor via its text content and then specifying the xpath to the input element:
//label[contains(text(), 'TEXT_TO_FIND')]
I am not sure how to do this in python though. My web element:
<div class="InputText">
<label for="INPUT">
<span>
LABEL TEXT
</span>
<span id="idd" class="Required" title="required">
*
</span>
</label>
<span class="Text">
<input id="INPUT" class="Text ColouredFocus" type="text" onchange="var wcall=wicketAjaxPost(';jsessionid= ... ;" maxlength="30" name="z1013400259" value=""></input>
</span>
<div class="RequiredLabel"> … </div>
<span> … </span>
</div>
Upvotes: 2
Views: 2376
Reputation: 363
Unfortunately I was not able to use CSS or XPATH expressions on the site. IDs and names always changed.
The only solution to my problem I found was a dirty one - parsing the source code of the page and extract the ids by string operations. Certainly this is not the way webdriver was intended to be used, but it works robustly.
Code:
lines = []
for line in driver.page_source.splitlines():
lines.append(line)
if 'LABEL TEXT 1' in line:
id_l1 = lines[-2].split('"', 2)[1]
Upvotes: 1
Reputation: 473893
You should start with a div and check that there is a label
with an appropriate span
inside, then get the input
element from the span
tag with class Text
:
//div[@class='InputText' and contains(label/span, 'TEXT_TO_FIND')]/span[@class='Text']/input
Upvotes: 0