簡體   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