Laura Hannah Vachon
Laura Hannah Vachon

Reputation: 133

Selenium web driver getting the text from the for attribute of a label using Ruby

I have seen some examples of how to do this in Javascript or python, but am looking for how to find the text of the for attribute on a label. e.g.

<label for="thisIsTheTextNeeded">LabelText</label> 
<input type="checkbox" id=thisIsTheTextNeeded">

We want to pick up the text from the for attribute on the label element. Then use that text as the id to find the checkbox.

The .NET solution might look like:

textWeNeed = selenium.getAttribute("//label[text()='LabelText']/@for");

I tried this in Ruby:

textWeNeed =
@browser.find_element("xpath//label[text()='LabelText']/@for")

and get the error:

expected "xpath//label[text()=input_value]/@for":String to respond to #shift (ArgumentError)

Any ideas?

Upvotes: 1

Views: 4897

Answers (4)

Werries
Werries

Reputation: 1

I found in Ruby when looking for Strings best to use is :find: instead of :find_element:

textWeNeed = @browser.find("xpath//label[text()='LabelText']/@for")

when presented with the error: "String to respond to #shift"

Upvotes: 0

Hiroki Kumazaki
Hiroki Kumazaki

Reputation: 388

find_element function requires Hash to search with xpath.

correct way is here,

textWeNeed =
@browser.find_element(xpath: "xpath//label[text()='LabelText']/@for")

below is wrong way(your code).

textWeNeed =
@browser.find_element("xpath//label[text()='LabelText']/@for")

Upvotes: 0

Laura Hannah Vachon
Laura Hannah Vachon

Reputation: 133

Here is how I fixed it. Thanks for all the help!

element = @browser.find_element(:xpath=>"//label[text()=\'#{input_value}\']")
attrValue = element.attribute('for') listElement =
@browser.find_element(:id=>"#{attrValue}")

Upvotes: 1

Saifur
Saifur

Reputation: 16201

You should use the attribute method to get the value of the attribute. See the doc

element = @browser.find_element(:xpath, "//label[text()='LabelText']")
attrValue = element.attribute("for")

According to OP's comment and provided html I think the element needs some explicit wait

wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds

element = wait.until { @browser.find_element(:xpath => "//label[contains(text(),'My list name')]") }
attrValue = element.attribute("for")

Upvotes: 0

Related Questions