Reputation: 209
I am sorry that if I ask a duplicate/stupid questions. I am confused with how to decide if an element exists. Errors:"Could not locate the id "smc"" will pop up if you run the following code.
if driver.find_element_by_id("smc"):
print("Yes")
else:
print("No")
The following code will be work:
try:
verification = driver.find_element_by_id("smc")
except NoSuchElementException:
print("No exits")
After I log in the page, it will enter one of the following options. Want to go the next step accordingly if one of the page has the "its own element".
1.1 page 1
-How to verify: driver.find_element_by_id("smc")
-Next step: func1()
1.2. page 2
-How to verify: driver.find_element_by_id("editPage")
-Next step: print("You need retry later") and exit the code
1.3. page 3
-How to verify: driver.find_element_by_id("cas2_ilecell")
-Next step: func2()
How do I complete my task? As I try to use "if" and it could not work....
Thank you very much.
Upvotes: 0
Views: 91
Reputation: 12255
You can write you own method to check if element exists, Java example:
public boolean isExist(WebDriver driver, By locator) {
try {
return driver.findElement(locator) != null;
} catch (WebDriverException | ElementNotFound elementNotFound) {
return false;
}
}
In python maybe it will look like(not sure!) this:
def isExist(driver, by, locator):
try:
return driver.find_element(by, locator) is None
except NoSuchElementException:
return False
Or
def isExist(driver, id):
try:
return driver.find_element_by_id(locator) is None
except NoSuchElementException:
return False
and use it:
if isExist(driver, "smc")
fun1()
Upvotes: 0
Reputation: 193108
As per your question to decide the three options and run the next step accordinglyyou can use the following solution :
You can write a function as test_me()
which will take an argument as the id
of the element and provide the status as follows:
def test_me(myString):
try:
driver.find_element_by_id(myString)
print("Exits")
except NoSuchElementException:
print("Doesn't exit")
Now you can call the function test_me()
from anywhere within your code as follows:
test_me("smc")
#or
test_me("editPage")
#
test_me("cas2_ilecell")
Upvotes: 0
Reputation: 52665
Try to replace
if driver.find_element_by_id("smc")
with
if driver.find_elements_by_id("smc")
Upvotes: 1
Reputation: 1439
You wrote the solution itself in your question. WebDriver throws NoSuchElementException
if it is not able to find the element with the given locator and you need to handle it using try-except if you want your code to go to to an alternate path.
Other option you can use, if you don't want to handle exceptions is driver.find_elements
. It returns a list of elements matching a locator and an empty list if it couldn't find any. So you will do something like -
count = len(driver.find_elements_by_id('some_id'))
if count == 0:
//element was not found.. do something else instead
Upvotes: 1