我是一名Python工程师,正在使用Selenium。我想知道如何判断HTML页面中是否存在指定XPath的元素。请问应该怎么做?
输出:True或False。
示例输入:
chek_if_exists("xpath")
输出:True或False。
您需要编写一个函数来检查元素是否存在。如果元素存在,该方法将返回True,如果无法找到元素并抛出异常,则返回False。
def hasXpath(xpath):
try:
self.browser.find_element_by_xpath(xpath)
return True
except:
return False
True
。
示例:
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))
return bool(root.xpath(xpath))
。 - Winny link <-"http://www.skelbiu.lt/skelbimai/diplominiai-lt-4792675.html"
首先,您需要获取响应:
response <- GET(link)
然后,加载文档:
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")
ifelse
语句并检查返回的属性内容的长度。