繁体   English   中英

如何检查硒(python 2)中是否存在某个元素,而没有抛出NoSuchElement异常呢?

[英]How do I check if an element is present in selenium (python 2) without throwing a NoSuchElement Exception if it isn't?

我想检查正在测试的页面上是否存在元素,但是我不希望find_element_by_xpath函数抛出NoSuchElement异常(如果不存在)。 这是我当前的代码:

try:
    self.driver.find_element_by_xpath(an_element)

    try:
        self.driver.find_element_by_xpath(another_element)

    except NoSuchElementException:
        ... (If the first find_element works and second doesn't I want this code)

except NoSuchElementException:
    ... (If the first find_element fails I want this code)

这本质上是作为if else语句起作用的,因此我宁愿使用if else语句,以便在这些代码块中找不到其他此类元素异常。

如果元素不存在,还有其他选项不会引发异常吗?

编辑:

给出的答案很棒! 感谢那些回答。 如果您正在阅读同样的问题,我也想出了另一种方法:

当使用find_element s _by_xpath()时,它将返回找到的元素的列表。 如果此列表的长度为0,则该元素不存在。 如果length为1,则存在一个元素。 没有引发异常。

您可以使用以下代码:

if self.driver.find_elements_by_xpath(an_element):
    if self.driver.find_elements_by_xpath(another_element):
        # code for case both found
    else:
        # second not found
else:
    # first not found

请注意, find_elements_by_xpath()返回WebElement列表或空列表。 无需处理NoSuchElementException

您可以搜索page_source,其中包含所有html标签和内容:

if '<button class="">' in self.driver.page_source:
    ... (do one thing)
else:
    ... (do another thing)

您拥有的代码对于执行这种操作是完全正确的。 在Python中,try / except是一个有效的控制结构,可以像这样使用,并且通常(几乎总是)比使用if / else块更有效。 您可能还想通过将代码分成不同的功能来简化代码,例如下面的示例(响应于编辑)。

class SomeClass(object):
    """Your class which is doing the scraping"""

    def find_element(self, xpath):
        """A handy function to try and find the element.

        Args:
            xpath (str): the xpath string you are trying to find

        Returns:
            List of elements
        """
        try:
            return self.driver.find_element_by_xpath(xpath)
        except NoSuchElementException:
            return []

    def find_buttons(self):
        """method to find your buttons

        Returns:
            list of buttons, or empty list if no buttons found
        """
        # define your queries
        xpaths = ['/some/query', '/some/other/query']

        # iterate through them
        for xpath in xpaths:
            buttons = self.find_element(xpath)
            if buttons:
                # until you are successful 
                return buttons

        # or return empty list if no buttons found
        return []

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM