【问题标题】:How to check if a element with specified xpath exists in the html document?如何检查html文档中是否存在具有指定xpath的元素?
【发布时间】:2015-06-19 06:55:15
【问题描述】:

我正在使用 python 中的 selenium 并想知道 html 页面中是否存在具有指定 xpath 的元素。我该怎么做?

样本输入:

chek_if_exists("xpath")

输出:TrueFalse

【问题讨论】:

  • 您可以简单地检查 xpath 的 web 元素是否存在。如果给定的 xpath 没有 webElement,则该 xpath 不存在。

标签: python selenium xpath


【解决方案1】:

您必须编写一个函数来检查元素是否存在。如果元素存在,该方法将返回 True,如果找不到元素并抛出异常,则返回 False。

def hasXpath(xpath):
    try:
        self.browser.find_element_by_xpath(xpath)
        return True
    except:
        return False

【讨论】:

    【解决方案2】:

    我们可能会编写返回 True 的函数是否存在 xpath

    演示:

    content = """<html>
        <head>
        </head>
        <body>
            <div class="start">
                <p>I am P</p>
            <div/>
            <div class="start">
                <p>I am P</p>
            <div/>
        </body> 
    </html>"""
    
    
    def isXpath(content, xpath):
        """
            Return True if Xpath present else return False
        """
        import lxml.html as PARSER
        root = PARSER.fromstring(content)
        if root.xpath(xpath):
            return True
        return False
    
    print "Debug 1:", isXpath(content, "//div[@class='start']")
    
    print "Debug 2:", isXpath(content, "//div[@id='start']")
    

    输出:

    Debug 1: True
    Debug 2: False
    

    我们可以使用以下代码替换上面代码中的if loop

    return bool(root.xpath(xpath))
    

    【讨论】:

    • 您可能希望将退货条件简化为return bool(root.xpath(xpath))
    • @Winny:是的,已添加到答案中。谢谢你。我以前不知道。
    【解决方案3】:

    假设您有链接:

      link <-"http://www.skelbiu.lt/skelbimai/diplominiai-lt-4792675.html"
    

    首先你会得到响应:

      response <- GET(link)
    

    然后,加载文档:

      doc <- content(response,type="text/html", encoding = "UTF-8")
    

    接下来,您要提取广告的标题。如果文本的长度不等于0,则可以通过检查条件来检查节点是否存在。如果存在,则存在该节点或文本,因此将返回“元素不存在”。

      name <- ifelse(length(xpathSApply(doc, "//title",xmlValue))!=0,
                            xpathSApply(doc, "//title",xmlValue),
                            "Element does not exist")
    

    这个最小示例的基本思想是使用ifelse 语句并检查返回的属性内容的长度。

    HTH

    【讨论】:

      猜你喜欢
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2017-02-21
      • 2011-08-07
      • 2021-09-19
      • 2022-01-05
      相关资源
      最近更新 更多