1

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?

har07
  • 88,338
  • 12
  • 84
  • 137
  • Found these good resource for path syntax http://stackoverflow.com/questions/3655549/xpath-containstext-some-string-doesnt-work-when-used-with-node-with-more and http://www.seleniumhq.org/docs/appendix_locating_techniques.jsp – Laura Hannah Vachon Apr 08 '15 at 14:11

4 Answers4

1

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}")
Saifur
  • 16,081
  • 6
  • 49
  • 73
0

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")
Saifur
  • 16,081
  • 6
  • 49
  • 73
0

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")
Hiroki Kumazaki
  • 389
  • 1
  • 5
0

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"

rene
  • 41,474
  • 78
  • 114
  • 152