【问题标题】:XPath query works on JS but not seleniumXPath 查询适用于 JS 但不适用于 selenium
【发布时间】:2021-01-01 15:22:21
【问题描述】:

我有这个(见下文)XPath 查询,它在 Javascript 上运行得很好,但它挂起,当然是因为它还没有找到元素,所以它正在等待超时。我该如何解决这个问题?

var span = driver.FindElement(By.XPath("//span[text() = \"What's your name?\"]/ancestor::div[@class=\"office-form-question-content office-form-theme-focus-border\"]//input[@class=\"office-form-question-textbox office-form-textfield-input form-control border-no-radius\"]"));

其中驱动程序是this 类型。 HTML 的目标部分如下所示:

<div class="office-form-question-content office-form-theme-focus-border">
  <div aria-live="assertive" role="alert"></div>
  <div class="question-title-box">
    <div>
      <div aria-level="2" class="office-form-question-title" id="question1-title" role="heading"><span class="ordinal-number">1.</span><span>What's your name?</span><span class="required-star"></span>
        <div><span class="accessibility-reader-no-display" id="question1-required">Requer resposta</span></div>
        <div><span class="accessibility-reader-no-display" id="question1-questiontype">Texto de linha única</span></div>
      </div>
    </div>
  </div>
  <div class="office-form-question-element">
    <div class="student-feedback-view-short-text-field-with-correctness">
      <div>
        <div class="office-form-textfield"><input class="office-form-question-textbox office-form-textfield-input form-control border-no-radius" aria-labelledby="question1-title question1-required question1-questiontype" placeholder="Insira sua resposta" spellcheck="true" maxlength="4000"
            value=""></div>
      </div>
    </div>
  </div>
</div>

【问题讨论】:

    标签: c# selenium firefox xpath


    【解决方案1】:

    我使用您的 xpath 表达式和 HTML sn-p 成功运行了它。

    driver.get("file:///C:/demo.html");
    
    String xpath = "//span[text() = \"What's your name?\"]/ancestor::div[@class=\"office-form-question-content office-form-theme-focus-border\"]//input[@class=\"office-form-question-textbox office-form-textfield-input form-control border-no-radius\"]";
    WebElement e = driver.findElement(By.xpath(xpath));
    e.sendKeys("quan");
    

    我的环境:

    Chrome 84.0.4147.125
    ChromeDriver 84.0.4147.30
    

    因此,“XPath 查询无法使用 selenium”可能不是真正的原因。

    【讨论】:

    • 这确实适用于那个小的本地 HTML 代码,但不适用于在线页面,我在那里复制那段 HTML。在它返回的 HTML 页面上:OpenQA.Selenium.NoSuchElementException: 'Unable to locate element: //span[text() = "What's your name?"]/ancestor::div[@class="office-form-question-content office-form-theme-focus-border"]//input[@class="office-form-question-textbox office-form-textfield-input form-control border-no-radius"]'
    猜你喜欢
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多