Trying if ellif in Appium Python - python

I need to check if user has already logged into the application. So I have to check for any of the 3 elements below mentioned are present. If anyone of them is present, user is logged in and I need to click sign out button.
The elements are :
1. sign out button already present(since user is already signed in )
2. Account name
My script is like :
if(wd.find_element_by_name("sign out").is_displayed()):
wd.find_element_by_name("sign out").click()
elif(wd.find_element_by_name("usr_name").is_displayed()):
wd.find_element_by_name("usr_name").click()
wd.find_element_by_name("menu_close").click()
wait("sign out")
wd.find_element_by_name("sign out").click()
else:
print"NOt Signed in"
But what happens is my appium is executing the first IF Loop and waiting for the element sign out and ends with an error message.
An element could not be located on the page using the given search parameters.
Where I am doing wrong ? Usually how can I check if an element is present then click it, like that. Please help me.

shouldn't the elif be unindented like this:
if(wd.find_element_by_name("sign out").is_displayed()):
wd.find_element_by_name("sign out").click()
elif(wd.find_element_by_name("usr_name").is_displayed()):
wd.find_element_by_name("usr_name").click()
wd.find_element_by_name("menu_close").click()
wait("sign out")
wd.find_element_by_name("sign out").click()
else:
print"NOt Signed in"

You should use wd.implicitly_wait(30) after each command, so that the appium server waits for next element to be visble

If you want to check an element is present before firing an action just create a method which returns a boolean value based on the isDisplayed property for the element.
Something like this :
def IsElementDisplayed():
try:
return wd.find_element_by_name("sign out").is_displayed()
except:
return false
And call the IsElementDisplayed before each action from the test sript.

Because there's no element that has the name "sign out", find_element_by_name() is throwing an exception that isn't being handled. One way to solve this is to write a wrapper for searching for elements that includes exception handling. As mentioned in another answer, setting the implicit wait bakes in waiting for elements to be present and repeatedly searches for the element until the timer expires (20s in the code below)
from selenium.common.exceptions import NoSuchElementException
wd.implicitly_wait(20)
sign_out = find_element("sign out")
usr_name = find_element("usr_name")
if sign_out is not None and sign_out.is_displayed():
sign_out.click()
elif usr_name is not None and usr_name.is_displayed():
usr_name.click()
menu_close = find_element("menu_close")
menu_close.click()
sign_out = find_element("sign out")
sign_out.click()
else:
print("Not signed in")
def find_element(self, element_text):
try:
element = wd.find_element_by_name(element_text)
except NoSuchElementException:
return None
return element

Related

How to know if element appear and then disappear in selenium python ' is_displayed() issues '

In the website i'm trying to automate, when the internet connection get lost a notification you can access to it by a class name appears at the top of the page and tells you that there is no internet and i want to code something that let you pause the process until the internet get back
and i'm tying to reack that by .is_displayed() which return a True value after checking that the notification appears and it's working fine but when i tried to check the disappear of the element it show me an error
except:
#time.sleep(3)
if driver.find_element(By.CLASS_NAME, "HGcYc4pY").size['width'] != 0 :
print ('internet lost')
while True:
c= driver.find_element(By.CLASS_NAME, "HGcYc4pY").is_displayed()
if driver.find_element(By.CLASS_NAME, "KhLQZTRq pxYtrw1j D56bmevE").is_displayed() == True:
print("still lost")
if driver.find_element(By.CLASS_NAME, "KhLQZTRq pxYtrw1j D56bmevE").is_displayed() == False:
print("interent is back")
break
print("did it ")
I tried this and it's just the same it doesn't work when the notification disappear aggain
except:
#time.sleep(3)
if driver.find_element(By.CLASS_NAME, "HGcYc4pY").size['width'] != 0 :
print ('internet lost')
while True:
if driver.find_element(By.CLASS_NAME, "HGcYc4pY").size['width'] != 0:
print("still lost")
if driver.find_element(By.CLASS_NAME, "HGcYc4pY").size['width'] == 0:
print("interent is back")
break
print("did it ")
I could not reproduce that. I mean, I disconnected my PC from the internet and got the "no internet" page but I could not see there elements with class name HGcYc4pY.
Anyway, what I can suggest here is: instead of find_element method you can use find_elements method. It will always return you a list of elements found matching the passed locator. In case there was matches the list will be non-empty, otherwise the list will be empty. Python interprets empty list as a Boolean False while non-empty list is interpreted as a Boolean True.
This approach will never throw exception in case of no element found.
So, you logic could be something like this:
if driver.find_elements(By.CLASS_NAME, "HGcYc4pY"):
#do whatever you need for the case the element is presented on the page
else:
#do whatever you want for the no element presented case

Else statement is not getting executed. IF statement is the only one being run? [duplicate]

This question already has answers here:
Checking if an element exists with Python Selenium
(14 answers)
Closed 2 years ago.
I have this script that goes to google takeout and downloads the takeout file. The issue I am having is, some accounts require a relogin when the "Takeout_dlbtn" is clicked and others can download directly. I tried to put this IF ELSE statement. Where if "password" is displayed, we run through the steps to re-enter password and then download. And if the "password" does not appear, we assume we do not need to login and can download right away.
The issue I am having is, my IF statement runs, and if the password page is shown, it will enter password and then download. But if the password page is not shown, the IF statement is still run and my ELSE statement does not get executed. It throws this error "no such element :Unable to locate element: {"Method":" css select","selector":"[name-"password"]"}"
How do I get the ELSE function to run if the "password" element is not shown? Any help would be appreciated.
def DLTakeout(self, email, password):
self.driver.get("https://takeout.google.com/")
time.sleep(2)
self.driver.find_element_by_xpath(takeout_DLbtn).click()
time.sleep(4)
if self.driver.find_element_by_name("password").is_displayed():
print("IF statement")
time.sleep(3)
self.driver.find_element_by_name("password").clear()
time.sleep(5)
self.driver.find_element_by_name("password").send_keys(password)
time.sleep(5)
self.driver.find_element_by_xpath("//*[#id='passwordNext']/div/button/div[2]").click()
print("Downloading")
logging.info("Downloading")
time.sleep(10) #change time.sleep to a higher number when download file is in gbs #1500
self.write_yaml(email)
print("Write to yaml successfully")
logging.info("Write to yaml successfully")
print("Zip move process about to start")
logging.info("Zip move process about to start")
time.sleep(4)
else:
print("else statement")
time.sleep(5)
print("Downloading")
logging.info("Downloading")
according to the Selenium docs:
4.2. Locating by Name
Use this when you know the name attribute of an element. With this
strategy, the first element with a matching name attribute will be
returned. If no element has a matching name attribute, a
NoSuchElementException will be raised.
So instead of if/else, try a try/catch block:
try:
self.driver.find_element_by_name("password")
print ("if statement")
...
except NoSuchElementException:
print ("else statement")
...

Selenium: Error comes using "if" to decide whether an element exists or not

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.
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
Try to replace
if driver.find_element_by_id("smc")
with
if driver.find_elements_by_id("smc")
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")
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()

Robotframework: Clicking web-elemnt in loop often fails to find an element

I have created a keyword for RF and Selenium2Library. It is supposed to wait for some element by clicking periodically on some other element which will renew the area where the element is supposed to appear. I use it for example for waiting for mails in postbox.
The problem is that pretty often the "renew element" cannot be found and clicked on some loop iteration however it exists on the screenshot. Any ideas why it can happen?
def check_if_element_appeared(self, element_locator, renew_locator, renew_interval=10, wait_interval=300):
if not self.is_visible(renew_locator):
raise AssertionError("Error Message")
start_time=int(time())
scan_time = start_time
if not self.is_visible(element_locator):
while int(time())<=start_time+wait_interval:
if int(time()) >= scan_time + renew_interval:
scan_time = int(time())
self.click_element(renew_locator)
if self.is_visible(element_locator):
break
if not self.is_visible(element_locator):
raise AssertionError("Error Message")
self._info("Message")
else:
self._info("Current page contains element '%s'." % element_locator)
Shouldn't be using the keywords Wait Until Page Contains Element or Wait Until Element Is Visible of the Selenium2Library for this purpose:
*** Test cases ***
Your Test Case
Prerequisite steps
Wait Until Page Contains Element ${locator}
Succeeding steps
Edit: Below is what your Python code might look like in pure Robot syntax.
${iteration}= Evaluate ${wait_interval} / ${renew_interval}
: FOR ${i} IN RANGE 0 ${iteration}
\ Click Element ${renew_locator}
\ Sleep 1
\ ${is_visible}= Run Keyword And Return Status Element Should Be Visible ${element_locator}
\ Exit For Loop If ${is_visible}
\ Run Keyword If '${is_visible}' == 'False' Sleep ${renew_interval}
Click Element ${element_locator}

Python Selenium is_displayed() returns true and ElementNotVisible exception is still raised?

Before calling any of the element's send_keys(), I first check if it's enabled and visible so it doesn't raise an exception.
What happens is is_Displayed returns True and when I try to send_keys to that element it still raises an exception of ElementNotVisible. Is this some form of a bug?
It works on some websites, it doesn't work on another.
def login():
elem = browser.find_elements_by_xpath('//input[contains(#name, "user")]')
for elements in elem:
if elements.is_displayed():
if elements.is_enabled():
elements.send_keys(username)
elem = browser.find_elements_by_xpath('//input[contains(#name, "pass")]')
for elements in elem:
if elements.is_displayed():
if elements.is_enabled():
elements.clear()
elements.send_keys(password + Keys.RETURN) #Crashes here
time.sleep(4)
return
Try this:
def login():
user_elements = browser.find_elements_by_xpath('//input[contains(#name, "user")]')
for user in user_elements:
if user.is_displayed():
if user.is_enabled():
user.send_keys(username)
pass_elements = browser.find_elements_by_xpath('//input[contains(#name, "pass")]')
for passw in pass_elements:
if passw.is_displayed():
if passw.is_enabled():
passw.clear()
passw.send_keys(password + Keys.RETURN) #Crashes here
time.sleep(4)
return
It's likely your choice of variable names make you clobber the outside loop with the inside loop.
If anyone is still wondering what problem was, it was caused by javascript hiding element after page was fully loaded.
Completely disabling javascript on page solved that issue.
pls use my code, my github https://github.com/big-vl/isdisplayed_selenium/blob/master/isDisplayed.py
def isDisplayed():
try:
browser.find_element_by_xpath("//*[text()='find text vwhis in page']")
except NoSuchElementException:
return False
return True
#use function
if (isDisplayed() == True):
print('text find, pleas replace hash tag or replace xpatch')
else:
print('not found text, my style php/python *smile*')

Categories