Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查html文档中是否存在具有指定xpath的元素?_Python_Selenium_Xpath - Fatal编程技术网

Python 如何检查html文档中是否存在具有指定xpath的元素?

Python 如何检查html文档中是否存在具有指定xpath的元素?,python,selenium,xpath,Python,Selenium,Xpath,我正在用python开发selenium,想知道html页面中是否存在具有指定xpath的元素。我怎么做 样本输入: chek_if_exists("xpath") 输出:True或False 我们可能正在编写一个函数,该函数返回的True为xpath存在 演示: content = """<html> <head> </head> <body> <div class="start">

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

样本输入:

chek_if_exists("xpath")
输出:
True
False


我们可能正在编写一个函数,该函数返回的
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循环

return bool(root.xpath(xpath))

假设您有链接:

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

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

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

您可以简单地检查xpath的web元素是否存在。如果给定的xpath没有webElement,则该xpath不存在。您可能希望将返回条件简化为
return bool(root.xpath(xpath))
@Winny:yes,在回答中添加。非常感谢。我以前不知道这个。
  doc <- content(response,type="text/html", encoding = "UTF-8")
  name <- ifelse(length(xpathSApply(doc, "//title",xmlValue))!=0,
                        xpathSApply(doc, "//title",xmlValue),
                        "Element does not exist")
def hasXpath(xpath):
    try:
        self.browser.find_element_by_xpath(xpath)
        return True
    except:
        return False