Selenium搜索元素,删除元素,然后验证元素是否被删除

2024-09-28 03:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的函数,我想搜索元素,如果找到元素,我想删除它,然后再搜索它。请参阅下面的代码:

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)这个删除找到的元素

^{pr2}$

3)然后我编写了一个函数来查看元素是否被删除。我不想再编写verify text函数,所以我使用了这个函数。这样写对吗?在

def verifyElement(self, text):
        if verifyText:
            raise Exception("Element could not be deleted")
        else:
            pass

Tags: 函数代码textself元素bydefelement
1条回答
网友
1楼 · 发布于 2024-09-28 03:18:33

您可以重新编写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"]和{}

{cd5>中可以使用它:

^{pr2}$

相关问题 更多 >

    热门问题