If Statements with Selenium using find element by xpath (contains text) - python

I am trying to find an element by text and depending if it is found or not print an output to the screen
This is what I have so far but I just cant get it to work
if driver.find_element_by_xpath("//*[contains(text(),'addFromWishlist')]").isEmpty()
{
System.out.println("In stock");
}
else{
System.out.println("Not In Stock");
}

Please use find_elements (plural) so that it would return a list of web element if found, if not it will return empty list. either way there won't be any exception.
try:
if len(driver.find_elements(By.XPATH, "//*[contains(text(),'addFromWishlist')]")) >0 :
print('In stock')
else:
print('Not In Stock')
except:
print('Something went wrong')
pass

Related

How to get an element from multiple elements until it's true in python selenium using try except

I am using python Selenium.
I need to check each for 5 elements until one of them is true, then return it.
My current code :
def status(self):
try:
elem = self.findelement(Objects.status_1)
if elem == True:
print("The status is : A")
elif self.findelement(Objects.status_2):
print("The status is : B")
elif self.findelement(Objects.status_3):
print("The status is : C")
elif self.findelement(Objects.status_4):
print("The status is : D")
else:
self.findelement(Objects.status_5)
print("The status is : E")
except Exception as e:
print(e)
raise AssertionError("Failed to fetch the status")
Note: The Objects.status is the directory of my locators file.
I want to get the status when it finds it. It will check one by one each element and when it finds the exact element it will stop and return the element.
So my expected output is :
The status is : D
You can simply change findelement to findelements and it will work. findelement method throws exception in case of no element found while findelements will return a list of element matching the passed locator. So, in case of match it will be a non-empty list interpreted by Python as a Boolean True while in case of no match it will return an empty list interpreted by Python as a Boolean False.
I hope your findelement internally applies Selenium find_element() method and findelements will implement Selenium find_elements() method.
So, your code could be as following:
def status(self):
try:
if self.findelements(Objects.status_1):
print("The status is : A")
elif self.findelements(Objects.status_2):
print("The status is : B")
elif self.findelements(Objects.status_3):
print("The status is : C")
elif self.findelements(Objects.status_4):
print("The status is : D")
elif self.findelements(Objects.status_5):
print("The status is : E")
except Exception as e:
print(e)
raise AssertionError("Failed to fetch the status")

How I can solve this Selenium If Elif problem?

I made a code to scrape some website. A list of IDs is iterated in the website, and it contains two conditions(If and Elif). But the problem is with the Elif. The error is it doesn't found the elif element (elem2).
I read in this question Python if elif else can't go to the elif statement Selenium the solution is a try/except, butI already used a Try/except to make works the if statement. What is a solution to make this code works with two conditions?
The code looks like this:
for item in list:
input = driver.find_element(By.ID, "busquedaRucId")
input.send_keys(item)
time.sleep(2)
elem1 = driver.find_element(By.ID, 'elem1')
elem1_displayed = elem1.is_displayed()
elem2 = driver.find_element(By.ID, 'elem2')
elem2_displayed = elem2.is_displayed()
try:
if elem1_displayed is True:
code to scrape given de first condition
elif elem2_displayed is True:
code to scrape given de second condition
except NoSuchElementException:
input = driver.find_element(By.ID, ('busquedaRucId')).clear()
Than you for any help. I'm stuck with this problem for two weeks.
I would restructure your code by wrapping the find_element function in a function which handles NoSuchElementExceptions by returning False, basically making the error silent:
def element_exists_and_displayed(driver, id):
try:
return driver.find_element(By.ID, id).is_displayed()
except NoSuchElementException:
return False
for item in list:
input = driver.find_element(By.ID, "busquedaRucId")
input.send_keys(item)
time.sleep(2)
if element_exists_and_displayed(driver, 'elem1'):
# code to scrape given first condition
pass
elif element_exists_and_displayed(driver, 'elem2'):
# code to scrape given second condition
pass
else:
driver.find_element(By.ID, ('busquedaRucId')).clear()

Creating a try and except statement that will try multiple conditions

while True:
try:
element = driver.find_element(By.XPATH, "//*[contains(#href,'dawson')]")
element.click()
break
except NoSuchElementException:
driver.refresh()
time.sleep(3)
Above is the try and except block that looks for a word in a Href and if it contains it the element is clicked. I wish to go through multiple of these given words and try them. So if the first word is not found it then goes on to the next word. It does not matter if it refreshes in between I just want it to iterate through these words and if it finds one it will click. How can I add more words into the try block?
Any help would be great.
Thank you
Search for an element in separate loop
def find_link_by_word_in_href(driver, words):
for word in words:
try:
return driver.find_element(By.XPATH, f"//*[contains(#href,'{word}')]")
except NoSuchElementException:
pass
while True:
element = find_link_by_word_in_href(driver, ['dawson', 'denbigh', 'and_so_on'])
if element is not None:
element.click()
break
else:
driver.refresh()
time.sleep(3)

How to try-except block exit when try is working

The code I have works. The last for loop gets reached and choice.click() gets clicked on. The question I have is why the except block gets executed even though the:
if choice.text == call_resource:
choice.click()
break
piece of the code is reached and the choice.click() portion works?
def select_choice(driver, resource_tag):
try:
call_resource = None
access_data = common.retrieve_tag_access_data()
for row in access_data["access_data"]:
if str(row["id"]) == resource_tag:
call_resource = row["row_tag"]["name"]
break
if call_resource is None:
access_data = common.retrieve_fixture_access_data()
for row in access_data["access_data"]:
if str(row["id"]) == resource_tag:
call_resource = row["row_tag"]["name"]
break
menu = driver.find_element_by_css_selector("ul[role='listgrid']")
choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
if choice.text == call_resource:
choice.click()
break
except:
error(logger, "unable to select choice")
pass
Because the last for loop works, shouldn't it break entirely out of the function after choice.click() without executing the except: portion of the code?
The except: portion will run only if an Exception occurred inside the try block. You should change the except: line to something like except Exception as e: and print the variable e in some way so you can discover what the problem is.
choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
if choice.text == call_resource:
choice.click()
break
Could be replaced with since your only trying to click one element with a certain text why not just try to find it. If it errors out it will go to the exception you provided.
driver.find_element(By.XPATH,f"//li[#role='choices' and contains(text(),{call_resource})]").click()
Also use to find errors use the following.
except Exception as e:
print(str(e))

trying to use continue or pass inside while loop but it doesnt seem to do work selenium

my program iterate between items, it clicks on the item, then clicks again and moves to the next item.
i am trying to make the program pass on an item if error accurs.
the excepts are inside a while loop, each item code seems like this:
item_1 = driver.find_element_by_id('feed_item_0')
item_1.location_once_scrolled_into_view
if item_1.is_displayed():
item_1.click()
time.sleep(2)
phone_reveal_1 = driver.find_element_by_id('phone_number_0')
contact_seller_1 = driver.find_element_by_id('contact_seller_0')
if phone_reveal_1.is_displayed():
phone_reveal_1.click()
elif contact_seller_1.is_displayed():
contact_seller_1.click()
elif not phone_reveal_1.is_displayed() or contact_seller_1.is_displayed():
continue
at the end i wrote this:
except selenium.common.exceptions.NoSuchElementException:
continue
except selenium.common.exceptions.ElementClickInterceptedException:
continue
except selenium.common.exceptions.StaleElementReferenceException:
continue
so what the code does is when any error accurs no matter if continue, or pass is written, the loop starts all over again from the start. i just want it to skip the item what. am i missing?
for anyone who will have the same issue, problem, was that i have handled the exceptions at the end. every block needs to have its own exception. the code should be like this:
try:
item_1 = driver.find_element_by_id('feed_item_0')
item_1.location_once_scrolled_into_view
if item_1.is_displayed():
item_1.click()
time.sleep(2)
phone_reveal_1 = driver.find_element_by_id('phone_number_0')
contact_seller_1 = driver.find_element_by_id('contact_seller_0')
if phone_reveal_1.is_displayed():
phone_reveal_1.click()
elif contact_seller_1.is_displayed():
contact_seller_1.click()
phone_numbers_1 = driver.find_elements_by_id('phone_number_0')
number_1 = [i.text for i in phone_numbers_1]
except NoSuchElementException:
pass

Categories