繁体   English   中英

Selenium Web驱动程序使用Ruby从标签的for属性获取文本

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

我已经看到了一些使用Javascript或python进行此操作的示例,但是正在寻找如何在标签上查找for属性的文本。 例如

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

我们要从label元素的for属性中拾取文本。 然后使用该文本作为ID来查找复选框。

.NET解决方案可能类似于:

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

我在Ruby中尝试过:

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

并得到错误:

预期的“ xpath // label [text()= input_value] / @ for”:响应#shift的字符串(ArgumentError)

有任何想法吗?

这是我固定的方法。 感谢您的所有帮助!

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

您应该使用attribute方法来获取属性的值。 参阅文件

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

根据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函数需要Hash使用xpath搜索。

正确的方法在这里

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

下面是错误的方式(您的代码)。

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

在Ruby中寻找最佳使用字符串时,我发现:find:而不是:find_element:

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

出现错误时:“字符串以响应#shift”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM