我有以下功能,我想搜索元素,如果找到元素我想删除它然后再次搜索它。请参阅下面的代码:
1)此代码验证存在的文本。
def verifyText(self, text):
try:
self.switchToFrame(*MainPageLocatars.FRAMEONE)
self.switchToFrame(*MainPageLocatars.SUBLISTFRAME)
try:
self.text.find_element_by_xpath('//td[text() = "%s"]' % text)
except:
self.text.find_element_by_xpath('//td/span[text() = "%s"]' % text)
except:
try:
self.text.find_element_by_xpath('//td[text() = "%s"]' % text)
except:
self.text.find_element_by_xpath('//td/span[text() = "%s"]' % text)
2)这个删除找到的元素
def deleteElement(self, text):
driver.find_element_by_id("deletebutton").click()
alert = self.driver.switch_to.alert
alert.accept()
3)然后我写了一个函数来查看元素是否被删除。我不想再次编写验证文本功能,所以我使用了它。这是写它的正确方法吗?
def verifyElement(self, text):
if verifyText:
raise Exception("Element could not be deleted")
else:
pass
答案 0 :(得分:1)
您可以重新编写verifyText()
,如下所示:
from selenium.common.exceptions import NoSuchElementException
def verifyText(self, text):
try:
self.switchToFrame(*MainPageLocatars.FRAMEONE)
self.switchToFrame(*MainPageLocatars.SUBLISTFRAME)
except:
pass # Just do nothing if switching to frame failed. I suppose that if it's not in frame, then it's in the main body
try:
return self.text.find_element_by_xpath('//td[.="%s"]' % text)
except NoSuchElementException:
return False # if element with specified text is not found
请注意,//td[.="%s"]
与//td[text()="%s"]
和//td/span[text()="%s"]
然后您可以在verifyElement()
:
def verifyElement(self, text):
if self.verifyText(text):
raise Exception("Element could not be deleted")
# no need to use "else: pass"