Creating a try and except statement that will try multiple conditions - python

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)

Related

Python Selenium using loop to check keywords

keywords = ['no stock','out of stock','not available']
n = 0
while True:
n+=1
print(f'now check {n} times')
for keyword in keywords:
if keyword in driver.page_source:
print(f'found {keyword}, refresh after 30 seconds')
time.sleep(30)
driver.get(url)
else:
print(f'could not find any of keyword')
break
Hi guys, hope you are doing well.
I am trying to use selenium and to check whether an item is available in a webpage. My idea is to put all keywords related to no stock in a list and loop every 30 seconds to check.
however, if I put a break on it, the code only scan the 1st item in list. Is there any way that to break the loop if all the three keywords are not in website?
Thanks for your help.
Maybe is this the logic you are looking for?
keywords = ['no stock','out of stock','not available']
n = 0
while True:
n+=1
print(f'now check {n} times')
keywords_found = 0
for keyword in keywords:
if keyword in driver.page_source:
keywords_found += 1
print(f'found {keyword}, {keywords_found} of {len(keywords)}')
if keywords_found == len(keywords):
print(f"We found the {len(keywords)} items of the list intot he page, so sleep and navigate")
time.sleep(30)
driver.get(url)
else:
print(f'could not the {len(keywords)} keywords, break')
break

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()

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

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

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

selenim web driver python repet code ultimate

how repeat code again again again this every work
I want the code below to always work and it should be repeated, and again this function should be repeated and not removed from the program.
def ref(self):
driver = self.driver
nextB2 = driver.find_element_by_xpath("""//section/span/button/span[#aria-label='Like']""")
nextB2.click()
time.sleep(5)
nextB3 = driver.find_element_by_xpath("""//section/span/button/span[#aria-label='Like']""")
nextB3.click()
time.sleep(6)
nextB4 = driver.find_element_by_xpath("""//section/span/button/span[#aria-label='Like']""")
nextB4.click()
time.sleep(7)
driver.refresh()
time.sleep(5)
driver.switch_to_frame('ref')
driver.refresh('ref')
you can use for loop with range to stop at perticular count like
for i in range(10): #10 times
ref() #function call
if you want it to run for ever
while True: #loop that never stops
ref()
you can use break and continue for conditional breaks
while True:
if foo == foo:
break #break or stop the while oop
elif foo == bar:
continue #skip current iteration and continue execution
else:
ref()

Categories