0

我正在尝试在 Watir 中选择和打印动态对象的文本。每次生成对象时,它都是一个随机字符串。不太清楚如何指向对象。

<dd itemprop="trait">
text
</dd>

我尝试使用 xpath 并指向 itemprop 属性,但是当我运行它时程序只是出错了。不确定 xpath 是否不可能,或者我的代码是否不正确。

def read_dd_itemprop(trait)
    itemprop_text = @@browser.element(:xpath, "//dd[@itemprop='" + trait + "')]").text
    p itemprop_text
end

堆栈跟踪:

  The given selector //dd[@itemprop='trait')] is either invalid or does not result in a WebElement. The following error occurred:
  InvalidSelectorError: Unable to locate an element with the xpath expression //dd[@itemprop='trait')] because of the following error:
  [Exception... "The expression is not a legal expression."  code: "12" nsresult: "0x805b0033 (SyntaxError)"  location: "file:///var/folders/bv/4z13hkpn095bytggxzrx4l9h0000gp/T/webdriver-profile20130715-7256-ihkq92/extensions/fxdriver@googlecode.com/components/driver_component.js Line: 5773"] (Selenium::WebDriver::Error::InvalidSelectorError)
  [remote server] file:///var/folders/bv/4z13hkpn095bytggxzrx4l9h0000gp/T/webdriver-profile20130715-7256-ihkq92/extensions/fxdriver@googlecode.com/components/driver_component.js:8379:in `FirefoxDriver.annotateInvalidSelectorError_'
  [remote server] file:///var/folders/bv/4z13hkpn095bytggxzrx4l9h0000gp/T/webdriver-profile20130715-7256-ihkq92/extensions/fxdriver@googlecode.com/components/driver_component.js:8410:in `FirefoxDriver.prototype.findElementInternal_'
  [remote server] file:///var/folders/bv/4z13hkpn095bytggxzrx4l9h0000gp/T/webdriver-profile20130715-7256-ihkq92/extensions/fxdriver@googlecode.com/components/driver_component.js:8414:in `FirefoxDriver.prototype.findElement'
  [remote server] file:///var/folders/bv/4z13hkpn095bytggxzrx4l9h0000gp/T/webdriver-profile20130715-7256-ihkq92/extensions/fxdriver@googlecode.com/components/command_processor.js:10421:in `DelayedCommand.prototype.executeInternal_/h'
  [remote server] file:///var/folders/bv/4z13hkpn095bytggxzrx4l9h0000gp/T/webdriver-profile20130715-7256-ihkq92/extensions/fxdriver@googlecode.com/components/command_processor.js:10426:in `DelayedCommand.prototype.executeInternal_'

我接近了吗?这是一个合理的方法,还是我应该采取不同的角度?

4

1 回答 1

1

你有一个额外的括号“)”。

itemprop_text = @@browser.element(:xpath, "//dd[@itemprop='" + object + "']").text

另请注意,我期望 xpath 是//dd[@itemprop='the value of object'],而不是//dd[@itemprop='object']. 请检查您object的值是否正确,例如应该是“trait”。

于 2013-07-15T05:11:04.937 回答