Selenium Python Exception even though Selenium succeeds and clicks - python

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

Related

Element click intercepted selenium

Seem to be getting this error when trying to click view more until the end of the page (until I don't see the view more option), but getting this error message
ElementClickInterceptedException 14 wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'select2-result-label'))).click()
15 while True:
---> 16 wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'view_more'))).click()
17 try:
18 element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'view_more')))
ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (231, 783)
(Session info: chrome=78.0.3904.108)
This is the code I have
while True:
wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'view_more'))).click()
try:
element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'view_more')))
element.click()
except TimeoutException:
break
Here is the html from the site
<a class="view_more" href="javascript:void(0);" onclick="_search('0')">VIEW MORE ...</a>
This is the website
page_link = 'http://beta.compuboxdata.com/fighter'
Firstly, Why do you have the same line of code duplicated in two different ways?
wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'view_more'))).click()
is functionally equivalent to:
try:
element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'view_more')))
element.click()
except TimeoutException:
break
save for handling the timeout exception.
I would just remove the first line, as I don't see the point in it.
On to your actual issue, see the answer to this stack overflow question: https://stackoverflow.com/a/44916498/3715974
My best guess is that it's due to a javascript/ajax call that's loading contents onto the page and the view more button isn't available immediately, causing your code to panic. Read through that answer and it may give you more insight, but you could also try simply catching that exception, delaying for a small period of time and trying again.

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....

Loop through find_element_by_name python selenium

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

Use python and selenium to delete my comments in reddit

I am trying to write a script to delete all my comments on my profile in Reddit.
So I am currently using Selenium to log-in and try to delete my comments, however I am stuck at the point when after my script press delete on my comment and it changes to "Are you sure Yes/No" then it can't find the "Yes" element by Xpath. The following code throws the error:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message:
Element is not currently visible and so may not be interacted with
Stacktrace:
My code is as follows:
del_button = driver.find_element_by_xpath("//*[contains(#id,'thing_"+delete_type+"')]//div[2]/ul/li[7]/form/span[1]/a")
del_button.click()
time.sleep(3)
yes_button = driver.find_element_by_xpath("//*[contains(#id,'thing_"+delete_type+"')]//div[2]/ul/li[7]/form/span[1]//a[1]")
yes_button.click()
time.sleep(3)
As there could be several hidden elements with same attributes on page, you might need to use index to click on exact element:
driver.find_elements_by_xpath('//a[#class="yes"]')‌​[N].clic‌​k() # N is the index of target link
I f you can't define exact index, you can use below code:
from selenium.common.exceptions import ElementNotVisibleException
for link in driver.find_elements_by_xpath('//a[#class="yes"]')‌:
try:
link.click()
break
except ElementNotVisibleException:
pass

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.

Categories

Resources