无法通过xpath定位元素

Unable to locate element by xpath

以下是源html:

1
2
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        Invalid username or password.

我真正需要的是检查是否显示消息"无效的用户名或密码。"(python selenium webdriver)。但是我很不幸使用xpath之类的

来找到它

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

因此,我决定使用消息文本查找确切的xpath。我已经尝试了多个选项,例如

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

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

但是每次都得到" NoSuchElementException:无法找到元素:{" method ":" xpath "," selector ":blablabla "

请咨询


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

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

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

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

1
assert"Invalid username or password." in alert_text

或者,删除" x"部分:

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

Python中的示例。


实际上,我发现我唯一需要的就是隐式等待。
该代码可以正常工作:

1
2
3
4
5
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的注释非常有用

You cannot directly point your expressions to the text nodes in Selenium.


能否提供更多信息,请:

-您是否单击按钮以获取消息?

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

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