[英]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. 我已经看到了一些使用Javascript或python进行此操作的示例,但是正在寻找如何在标签上查找for属性的文本。 eg
例如
<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. 我们要从label元素的for属性中拾取文本。 Then use that text as the id to find the checkbox.
然后使用该文本作为ID来查找复选框。
The .NET solution might look like: .NET解决方案可能类似于:
textWeNeed = selenium.getAttribute("//label[text()='LabelText']/@for");
I tried this in Ruby: 我在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)
预期的“ xpath // label [text()= input_value] / @ for”:响应#shift的字符串(ArgumentError)
Any ideas? 有任何想法吗?
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}")
You should use the attribute method to get the value of the attribute. 您应该使用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 根据OP的评论并提供html,我认为该元素需要一些明确的等待
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")
find_element
function requires Hash
to search with xpath. find_element
函数需要Hash
使用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")
I found in Ruby when looking for Strings best to use is :find: instead of :find_element: 在Ruby中寻找最佳使用字符串时,我发现:find:而不是:find_element:
textWeNeed = @browser. find ("xpath//label[text()='LabelText']/@for")
when presented with the error: "String to respond to #shift" 出现错误时:“字符串以响应#shift”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.