是否可以使用xpath获取输入值以搜索相应标签的值?

时间:2013-03-05 16:04:42

标签: ruby xpath selenium-webdriver

鉴于此HTML标记:

<tr>
  <td class="label">Description</td>
  <td class="data"><div>QA Test Customer</div></td>
</tr>

尝试编写一个Ruby方法,该方法将采用两个参数“描述”和“QA测试客户”,并使用Selenium WebDriver和XPath断言带有“描述”标签的输入值实际上是“QA测试客户”

不熟悉xpath,所以我很难挣扎。我知道我需要一个xpath字符串:

"find a <td> with class of 'label' that has a value of 'Description' then get the value of the <div> embedded in the following <td> with class of 'data'

任何指针都非常感谢!!

2 个答案:

答案 0 :(得分:1)

//td[@class='label' and .='Description']/following-sibling::td[@class='data']/div

答案 1 :(得分:1)

这是为Nokogiri写的。我不知道Selenium是否使用了Nokogiri,或者它自己的XML解析器,所以它可能无济于事....

我更喜欢CSS,因为它通常不那么冗长,也更容易理解:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<tr>
  <td class="label">Description</td>
  <td class="data"><div>QA Test Customer</div></td>
</tr>
EOT

doc.at('td.label + td.data').text
=> "QA Test Customer"

doc.at('td.label + td.data').text == 'QA Test Customer'
=> true

这只是寻找第一个<td class="label">,后面是<td class="data">的兄弟,但我们也可以添加对文本的搜索:

!!doc.at(%Q/td[class="label"]:contains("Description") + td[class="data"] div:contains("QA Test Customer")/)
=> true

将其转换为可以调用的方法:

def td_match(doc, s1, s2)
  !!doc.at(%Q/td[class="label"]:contains("#{ s1 }") + td[class="data"] div:contains("#{ s2 }")/)
end

在IRB中调用它:

irb(main):024:0> def td_match(doc, s1, s2)
irb(main):025:1>     !!doc.at(%Q/td[class="label"]:contains("#{ s1 }") + td[class="data"] div:contains("#{ s2 }")/)
irb(main):026:1>   end
=> nil
irb(main):027:0> td_match(doc, 'Description', 'QA Test Customer')
=> true

稍微清理一下:

def td_match(doc, s1, s2)
  !!doc.at(
    %Q/td[class="label"]:contains("#{ s1 }") + td[class="data"] div:contains("#{ s2 }")/
  )
end

或者,将它添加到Nokogiri :: HTML :: Document:

class Nokogiri::HTML::Document
  def td_match(s1, s2)
    !!self.at(
      %Q/td[class="label"]:contains("#{ s1 }") + td[class="data"] div:contains("#{ s2 }")/
    )
  end
end

doc.td_match('Description', 'QA Test Customer')
=> true