【问题标题】:Unable to locate element by xpath无法通过 xpath 定位元素
【发布时间】:2016-07-09 13:29:02
【问题描述】:

这里是源代码:

<div id="alert_signin" class="alert_modal_error">
    <div class="alert alert-danger alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        Invalid username or password.
    </div>
</div>

我真正需要的是检查消息“无效的用户名或密码”。出现(python + selenium webdriver)。但是我很不幸地发现它使用 xpath 之类的

find_element_by_xpath('//div[@id=\'alert_signin\']/div[@class=\'alert\']').text

所以我决定使用消息文本找到确切的 xpath。我尝试了几种选择,例如

find_element_by_xpath('//*[text()[contains(.,\'Invalid\')]]')

find_element_by_xpath('//*[contains(., \'Invalid username or password.\')]')

但每次都得到"NoSuchElementException: Unable to locate element: {"method":"xpath","selector": blablabla"

请指教

【问题讨论】:

    标签: xpath


    【解决方案1】:

    不能将表达式直接指向 Selenium 中的文本节点。

    相反,我会得到整个“警报”文本:

    alert_text = driver.find_element_by_css_selector("#alert_signin .alert").text
    

    然后,您可以应用“包含”检查:

    assert "Invalid username or password." in alert_text
    

    或者,删除“x”部分:

    alert_text = alert_text.replace(u"×", "").strip()
    assert alert_text == "Invalid username or password."
    

    Python 中的示例。

    【讨论】:

    • 我对 alert_text = driver.find_element_by_css_selector(".alert_signin .alert").text 有点困惑 - 它给了我 NoSuchElementException: Unable to locate element: {"method":"css selector ","selector":".alert_signin .alert"}
    • @yegres 啊,是的,是选择器中的错误 - 现在检查一下。谢谢。
    • 结果相同(请注意描述中的所有 div 元素都是嵌套的。
    【解决方案2】:

    请提供更多信息:

    -- 是否有一个按钮,您可以单击以获取消息?

    -- 消息是在特定于浏览器的警报中,还是页面上显示的文本?

    (如果是后者,请尝试if "Invalid username or password." in driver.page_source: print "SUCCESS!")

    【讨论】:

      【解决方案3】:

      实际上我发现我唯一需要的是使用implicitly_wait。 此代码工作正常:

      sign_in.click()
      driver.implicitly_wait(30)
      alert_text = driver.find_element_by_css_selector("div#alert_signin > div.alert.alert-danger.alert-dismissable").text
      alert_text = alert_text.replace(u"×", "").strip()
      assert alert_text == "Invalid username or password."
      

      但是,当我尝试验证我的方法时,来自 alecxe 的注释非常有用

      您不能直接将表达式指向 Selenium 中的文本节点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-01
        • 2019-12-25
        • 1970-01-01
        相关资源
        最近更新 更多