Make Python continue if doesnt find html element - python

im new to Python, and everything that i know i learned by myself so i have a huge gap in some things like language structure, it would be awsome if someone could help me.
Im building something with selenium and openpyxl and i face a problem, if it doesnt find an element the code stops there, and thats exactly what im trying to bypass without any success. I need to continue if the element not found.
Heres a piece of my currently code, can someone help me how can i do that?
Thanks
#distin_city varia
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[11]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/div[1]/span[1]"))).click()
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[11]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/input[1]")))
element.send_keys(destin_city[:3])
time.sleep(0.2)
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[11]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/ul[1]/li[1]/div[3]/span[1]/div[1]"))).click()
print("DESTINATION CITY - ",destin_city)
#f_payment varia
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[12]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/div[1]/span[1]/span[1]"))).click()
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[12]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/input[1]")))
element.send_keys(f_payment[:3])
time.sleep(0.2)
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[12]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/ul[1]/li[1]/div[3]/span[1]/div[1]"))).click()
print("FREIGHT PAYMENT TYPE - ",f_payment)
#currency varia
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[13]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/div[1]/span[1]"))).click()
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[13]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/input[1]")))
element.send_keys(currency[:1])
time.sleep(0.2)
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[13]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/ul[1]/li[1]/div[3]/span[1]/div[1]"))).click()
print("CURRENCY - ",currency)

In order to simply continue with the flow in case the element is not found you can use try-except block with pass in except section.
For example if you want to apply that on
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[11]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/div[1]/span[1]"))).click()
You can do this:
try:
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/ivd-form-field[11]/div[1]/div[1]/ivd-field[1]/div[1]/ivd-select-box-field[1]/div[1]/div[1]/div[1]/span[1]"))).click()
except Exception:
pass

What you're looking for is try, except. Say you want one or multiple lines to be checked. If anything failed there you can do something else (Or in your example do nothing and pass)
You wrap your line(s) with try, except.
try:
# This is your code
Do Something 1
Do something 2
except:
# This is your code when any line above fails. You can use `pass` to do nothing
Do something else

Related

Selenium won't fetch text fomr webelement (Python)

I have the following code in Python/Selenium:
try:
main = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "main"))
)
print(main.text)
except:
driver.quit()
And expecting a print statement but the "try" block seems to fail. I have all the right packages imported and what not but no dice. I am following along with a tutorial and everything has been working fine up to this point. Am happy to post the file thus far if needed. But just wondering why it is failing every pass. Any input is appreciated! Thanks!
EDIT: So I'm just tryna fetch/print the main content of the page given by:
<main id="main" class="site-main" role="main">...</main> ==$0
I have basically zero knowledge of html and I am just trying to follow along with a tutorial so I have no idea why its throwing errors.
Have you tried this:
print(main.get_attribute("innerHTML"))
or
print(main.get_attribute("outerHTML"))

Message: no such element: Unable to locate element python selenium

i have this error in selenium python
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[1]"}
i want the element with this xpath:
driver.find_element_by_xpath("/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[1]").click()
if doesn't exist, then click other element with other xpath like:
driver.find_element_by_xpath("/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[2]").click()
everything is clear if element 1 doesn't exists to click, click to element 2
how can I do this in selenium python
thanks
NoSuchElementException generally occurs because of one the below reasons
Element locator is incorrect
Element is not rendered
Page is not rendered or loaded
Element is inside a frame
You can have a look, do a debug and based on that write your code. :)
This is not the exact solution, but this is the idea
if elem1.is_displayed():
elem1.click()
else:
elem2.click()
I'd suggest you using time.sleep(10) and a nested try block to catch your errors while it accomplishes what you want to do. For example:
time.sleep(10)
try:
driver.find_element_by_xpath("/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[1]").click()
except:
print("button1 could not be found... Now trying to retreive button2")
try:
driver.find_element_by_xpath("/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[2]").click()
except:
print("button1 nor button2 were not found...")
Note that the time.sleep(10) delays your code from executing anything after this line for 10 seconds, and this allows the page to load properly for elements to be located easier.

Python Selenium - Close Driver When Text is no longer found

Hi I am using selenium to automate test on web pages. I am using selenium and python and would like to have answers in this framework only. I run looping script to check if text is still found or not, if not then close the browser.I have tried my script but only working when text has link on it
while True:
try:
element = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "My Text"))
)
except:
break
driver.close()
driver.quit()
that script is working when text has link, The problem is my text was pure text without any link. i cannot use css selector because the text changing after certain minutes, so i need to locate text not xpath or other. Hope someone can help. thank you
You are using By.PARTIAL_LINK_TEXT which is designed to only find text inside links.
If you want to lookup text in all elements, you need to use XPATH:
EC.presence_of_element_located((By.XPATH, "//*[contains(text(), 'My Text')]"))
See for reference:
https://stackoverflow.com/a/18701085/14241710
try that out, might help:
def check_no_longer_present(text):
try:
if driver.find_element_by_xpath("//[contains(text(), '{}')".format(text)).is_displayed():
return False
except NoSuchElementException:
return True
if check_no_longer_present('you_text'):
driver.quit()

Python selenium presence_of_element_located with only href

I am trying to click on a link in a forum using Selenium, but I need to wait until the page load, so i thought the better way was to use WebDriverWait. This is my code I used to test it:
driver.get("https://testocolo.forumcommunity.net")
#First click, working
driver.find_element_by_xpath('//a[#href="'+"/?f=9087616"+'"]').click()
try :
element = WebDriverWait(driver, 2).until(
EC.presence_of_element_located(By.XPATH, '//a[#href="'+"/?t=61904616"+'"]')
)
element.click()
except :
print("NO")
This is the element
Brotha
The try except cycle ends up every time printing "NO".
Before that I tried locating by LINK_TEXT instead, with 'Brotha' but in neither way works. Where am I doing wrong?
xpath you can try
//a[contains(#tittle,'discussione inviata il')]
or
//*[text()='Brotha']
Next option you can check is if that element is in iframe?
WebDriverWait(driver, 30).until(
EC.element_to_be_clickable((By.XPATH, "//*[text()='Brotha']")))

How can I check next iteration in for loop?

I am trying to scrape a JS website. I used Selenium and everything works well until I got this error. The website has a table and I am working on it.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[26]/td[4]"}
(Session info: chrome=84.0.4147.125)
In the XPath
25th and 27th iterations have 4. td
/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[26]/td[4]
but 26th doesn't have a 4th td.
I try to solve the problem with using "pass in loop" like this:
if(bool(driver.find_element_by_xpath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[26]/td[***+str(j)+***] ").is_enabled)):pass
But as soon as selenium sees the path it is giving an error without checking. I understand that "is_enable" method works for nothing.
The question is: how can I pass the iteration without Selenium interrupt?
try:
driver.find_element_by_xpath("./html/body/table/tbody/tr[2]/td["+str(j)+"]/table/tbody/tr["+str(i)+"]/td[4]")
except NoSuchElementException:
continue
If there is no element in the XPath, It returns null. It works. Thank you #JaSon
Have you tried something like this? (You can easily boot it up with for loop)
if driver.find_element_by_xpath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[26]/td[1(Can't boosted with for loop):
print("Found object")
else:
print("Can't find object")

Categories

Resources