Loop through find_element_by_name python selenium - python

I have a code where it looks for a name and I am trying to write an if statement that says if it can't find that name look for something else.
What I have so far is as follows:
excel = driver.find_element_by_name("Export to Excel")
if excel == None:
driver.implicitly_wait(15)
search = driver.find_element_by_xpath("//span[#id='inplaceSearchDiv_WPQ2_lsimgspan']")
search.click()
else:
excel.click()
I know what's inside the if statement works because I tested it out. Am I suppoed to change my argument in my if statement? The error I get is selenium.common.exceptions.NoSuchElementException: Message: No such element I tried entering "No such element" instead of "None" but I still get the same error. Also it tells me Exception Unhandled NoSuchElementException('No such element', None, None) can some give me advise on what I am doing wrong with the if statement? The error also say that it is found at excel = driver.find_element_by_name("Export to Excel") when the button isn't present in the page. When it is, it'll go straight to the else part of the statement

The find_element_by_name method on your driver will raise the NoSuchElementException exception if it cannot find the webelement.
Try this
from selenium.common.exceptions import NoSuchElementException
try:
excel = driver.find_element_by_name("Export to Excel")
excel.click()
except NoSuchElementException:
driver.implicitly_wait(15)
search = driver.find_element_by_xpath("//span[#id='inplaceSearchDiv_WPQ2_lsimgspan']")
search.click()

Related

Selenium Python Exception even though Selenium succeeds and clicks

in short I am getting an exception after the code that gives the exception suceeds.
def checkelementid(id1):
try:
second_driver.find_element_by_id(id1).click()
except NoSuchElementException:
return False
except ElementNotInteractableException:
return False
return True
if checkelementid("requisitionDescriptionInterface.UP_APPLY_ON_REQ.row1"):
print("before")
second_driver.find_element_by_id("requisitionDescriptionInterface.UP_APPLY_ON_REQ.row1").click()
print("after")
I get the following error after the click succeeds and I go to a new url:
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="requisitionDescriptionInterface.UP_APPLY_ON_REQ.row1"]
So it actually finds the element and clicks and get taken to a new site but it somehow runs the click again on the new site but obviously cant find the element. It prints "before" but does not print "after".
Try to put wait before if condition.
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

python script to open a page and click download

I am trying to open a page and click on download button. It works fine for the pages that have download element but for the pages which doesn't have that element it raises error
Code:
for i in data["allurl"]:
driver.get('{0}'.format(i))
if(driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')):
button_element = driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')
button_element.click()
else:
pass
It should pass instead of raising the error but when I run this it says:
NoSuchElementException: Message: no such element: Unable to locate
element:
{"method":"id","selector":"ContentPlaceHolder1_grdFileUpload_lnkDownload_0"}
How do I solve this?
driver.find_element_by_id() doesn't return True or False as your if-statement expects. Either change your if-statement, or use a try/except statement.
from selenium.common.exceptions import NoSuchElementException
for i in data["allurl"]:
driver.get('{0}'.format(i))
try:
button_element = driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')
button_element.click()
except NoSuchElementException:
pass
Check the length count of the web element.If it is more than 0 then element available and click otherwise it will go to else condition.
for i in data["allurl"]:
driver.get('{0}'.format(i))
if len(driver.find_elements_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0'))>0:
button_element = driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')
button_element.click()
else:
pass
from selenium.common.exceptions import NoSuchElementException
try:
button_element = driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')
except NoSuchElementException:
pass
else:
button_element.click()
Note that even if it worked as you expected, it's inefficient because you perform search for the element twice.
EDIT: included the import statement for the exception
UPDATE: as a side note, assuming elements in data["allurl"] are url (i.e. strings) there is no need for string formatting. driver.get(i) would do. And i is poor choice for variable name - better use something more meaningful....

How to use the try/except with Selenium Webdriver when having Exceptions on Python

I'm trying the use a try/except statement to findout if an element exists in the WebDrive or not, if so then run a specific code line,
try:
WebDriver.find_element_by_css_selector('div[class="..."')
except NoSuchElement:
ActionToRunInCaseNoSuchElementTrue
else:
ActionToRunInCaseNoSuchElementFalse
but running this code gives an error:
NameError: name 'NoSuchElement' is not defined
how should the Exception be defined?
Is there any shorter/easier way to check if an element does exist in a web page and run a command if so and another if not?
To be able to use required exception you have to import it first with correct name (NoSuchElement -> NoSuchElementException):
from selenium.common.exceptions import NoSuchElementException
try:
WebDriver.find_element_by_css_selector('div[class="..."')
except NoSuchElementException:
ActionToRunInCaseNoSuchElementTrue
Instead of using try except you can use find_elements and check if the returned list has any elements
elements = WebDriver.find_elements_by_css_selector('div[class="..."')
if not elements:
ActionToRunInCaseNoSuchElementTrue
else:
ActionToRunInCaseNoSuchElementFalse
# the element is in elements[0]

How can I ignore the exception in Selenium?

I use Python Selenium for scraping a website,
but my crawler stopped because of a exception:
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
How can i continue to crawl even if the element is not attached?
UPDATE
i change my code to:
try:
libelle1 = prod.find_element_by_css_selector('.em11')
libelle1produit = libelle1.text # libelle1 OK
libelle1produit = libelle1produit.decode('utf-8', 'strict')
except StaleElementReferenceException:
pass
but i have this exception
NoSuchElementException: Message: no such element
i also tried this one:
try:
libelle1 = prod.find_element_by_css_selector('.em11')
libelle1produit = libelle1.text # libelle1 OK
libelle1produit = libelle1produit.decode('utf-8', 'strict')
except :
pass
Put a try-except block around the piece of code that produced that error.
To be more specific about what John Gordon is talking about. Handle the StaleElementReferenceException common selenium exception and ignore it:
from selenium.common.exceptions import StaleElementReferenceException
try:
element.click()
except StaleElementReferenceException: # ignore this error
pass # TODO: consider logging the exception
It looks like the browser rendering engine or Javascript engine is using the element and it is blocking other external operations on this element. You can attempt to access it after some time. If it is not accessible for longer duration, an exception can be thrown. Some good examples are given here.

clicking slippery "ElementNotVisibleException" button selenium webdriver python

https://gist.github.com/codyc4321/724f05aca8f6775e2fc1
Hi, bitbucket changed their login page, and is giving me a hassle. Based on the following gist, using driver.click_button causes:
ElementNotVisibleException at /bitbucket/create-repo
Message: Element is not currently visible and so may not be interacted with
Stacktrace:
at fxdriver.preconditions.visible (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:9981)
at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:12517)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:12534)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:12539)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:12481)
using driver.submit_form causes error in the browser itself:
using driver.activate_hidden_element causes:
ElementNotVisibleException at /bitbucket/create-repo
Message: Element is not currently visible and so may not be interacted with
activate_hidden_element failing really took the wind outta my sails for the last 5 minutes. How can I click this stonewalling button? Thank you
Okay, so the problem is actually in your locate_element method.
When you check for the xpath: "//button[normalize-space(text())='{text}']" it finds a button successfully but it is not the login button you are looking for. If you switch that with the input xpath: "//input[#value='{text}']" it finds the right input and successfully logs you in.
You should also remove the last two lines in the BitbucketDriver.login() method because the line self.click_button(search_text="Log in") throws an AttributeError.
Your locate_element method should look like this:
def locate_element(self, search_text, xpaths=None):
if not xpaths:
xpaths = [ "//input[#value='{text}']", "//button[normalize-space(text())='{text}']",
"//a[child::span[normalize-space(text())='{text}']]", "//a[normalize-space(text())='{text}']"]
try:
return self.driver.find_element_by_id(search_text)
except:
try:
return self.driver.find_element_by_name(search_text)
except:
try:
return self.driver.find_element_by_class_name(search_text)
except:
for path in xpaths:
try:
return self.driver.find_element_by_xpath(path.format(text=search_text))
except:
pass
return None

Categories

Resources