我试图验证页面上是否存在该文本.通过ID验证元素很简单,尝试使用文本进行操作是不正常的.并且,我找不到By的正确属性来验证网页上的文本.
使用By属性为ID工作的示例
self.assertTrue(self.is_element_present(By.ID, "FOO"))
Run Code Online (Sandbox Code Playgroud)
示例我尝试使用By属性使用(不起作用)文本
self.assertTrue(self.is_element_present(By.TEXT, "BAR"))
Run Code Online (Sandbox Code Playgroud)
我也试过这些,有*错误(下面)
self.assertTrue(self.is_text_present("FOO"))
Run Code Online (Sandbox Code Playgroud)
和
self.assertTrue(self.driver.is_text_present("FOO"))
Run Code Online (Sandbox Code Playgroud)
*error:AttributeError:'WebDriver'对象没有属性'is_element_present'
在尝试验证时我也有同样的问题By.Image.
从我所看到的,is_element_present是由Firefox扩展(Selenium IDE)生成的,如下所示:
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException: return False
return True
Run Code Online (Sandbox Code Playgroud)
"by"是从selenium.webdriver.common导入的:
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
Run Code Online (Sandbox Code Playgroud)
有几个"By"常量来解决每个API find_element_by_*所以,例如:
self.assertTrue(self.is_element_present(By.LINK_TEXT, "My link"))
Run Code Online (Sandbox Code Playgroud)
验证链接是否存在,如果不存在,则避免由selenium引发的异常,从而允许适当的单元测试行为.
首先,不鼓励这样做,最好改变你的测试逻辑,而不是在页面中查找文本。
is_text_present如果您确实想使用它,以下是您创建自己的方法的方法:
def is_text_present(self, text):
try:
body = self.driver.find_element_by_tag_name("body") # find body tag element
except NoSuchElementException, e:
return False
return text in body.text # check if the text is in body's text
Run Code Online (Sandbox Code Playgroud)
对于图像,逻辑是将定位器传递给它。(我认为 WebDriver API 中不is_element_present存在,不确定你是如何By.ID工作的,让我们假设它正在工作。)
self.assertTrue(self.is_element_present(By.ID, "the id of your image"))
# alternatively, there are others like CSS_SELECTOR, XPATH, etc.
# self.assertTrue(self.is_element_present(By.CSS_SELECTOR, "the css selector of your image"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19782 次 |
| 最近记录: |