Reputation: 2250
I am working on selenium in python and want to know if a element with th e specified xpath exists in the html page or not. How can I do it?
Sample input:
chek_if_exists("xpath")
Output:
True
orFalse
Upvotes: 3
Views: 13361
Reputation: 1914
Lets say you have link:
link <-"http://www.skelbiu.lt/skelbimai/diplominiai-lt-4792675.html"
First you get the response:
response <- GET(link)
Then, load the document:
doc <- content(response,type="text/html", encoding = "UTF-8")
Next, you want to extract the header of the advertisement. You can check whether the node exist by checking the condition if the length of the text is not equal to 0. If so, then there is such node or text so the "Element does not exist" will be returned.
name <- ifelse(length(xpathSApply(doc, "//title",xmlValue))!=0,
xpathSApply(doc, "//title",xmlValue),
"Element does not exist")
The basic idea of this minimal example is to employ ifelse
statement and checking the length of the returned attribute content.
HTH
Upvotes: 0
Reputation: 2291
You will have to write a function to check if the element exist or not. The method will return True if element exist and False if it fails to find the element and throws the exception.
def hasXpath(xpath):
try:
self.browser.find_element_by_xpath(xpath)
return True
except:
return False
Upvotes: 6
Reputation: 10223
We might be write function which return True
is xpath is present
Demo:
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']")
Output:
Debug 1: True
Debug 2: False
We can use following for replace of if loop
in above code:
return bool(root.xpath(xpath))
Upvotes: 2