Python Selenium stale element exception - python

I study Django and TDD. There is code (functional test) which verifies entry form to be located in center.
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class NewVisitorTest(LiveServerTestCase):
"""
Test Class
"""
def setUp(self):
self.browser = webdriver.Chrome()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_layout_and_styling(self):
self.browser.get(self.live_server_url)
self.browser.set_window_size(1024, 768)
inputbox = self.browser.find_element_by_id('id_new_item')
self.assertAlmostEqual(
inputbox.location['x'] + inputbox.size['width'] / 2,
512, delta=10
)
inputbox.send_keys('testing\n')
inputbox = self.browser.find_element_by_id('id_new_item')
self.assertAlmostEqual(
inputbox.location['x'] + inputbox.size['width'] / 2,
512, delta=10
)
The error occurs:
======================================================================
ERROR: test_layout_and_styling (functional_tests.tests.NewVisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "e:\Education\ttd\superlists\functional_tests\tests.py", line 112, in tes
t_layout_and_styling
inputbox.location['x'] + inputbox.size['width'] / 2,
File "c:\Program Files\Python34\lib\site-packages\selenium\webdriver\remote\we
belement.py", line 358, in location
old_loc = self._execute(Command.GET_ELEMENT_LOCATION)['value']
File "c:\Program Files\Python34\lib\site-packages\selenium\webdriver\remote\we
belement.py", line 448, in _execute
return self._parent.execute(command, params)
File "c:\Program Files\Python34\lib\site-packages\selenium\webdriver\remote\we
bdriver.py", line 196, in execute
self.error_handler.check_response(response)
File "c:\Program Files\Python34\lib\site-packages\selenium\webdriver\remote\er
rorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale elemen
t reference: element is not attached to the page document
(Session info: chrome=44.0.2403.155)
(Driver info: chromedriver=2.18.343845 (73dd713ba7fbfb73cbb514e62641d8c96a9468
2a),platform=Windows NT 6.1 SP1 x86_64)
With Firefox it works OK.
I tried also:
from selenium.webdriver.support.ui import WebDriverWait
...
...
def find(driver):
element = driver.find_elements_by_id("data")
if element:
return element
else:
return False
element = WebDriverWait(driver, secs).until(find)
Also, I tryed: self.browser.implicitly_wait(3), but it does not help. I have the latest updates of Selenium and ChromeDriver. Please, advise what is wrong with it?
I read similar questions on stackoverflow but it also does not help.
Thank you!

inputbox.send_keys('testing\n')
I would like to bet that your form is responding the newline and submitting itself. So by the time you do the assertion the page displayed in the browser has changed or is in the process of being changed.

Related

AttributeError Py

New to Python Selenium.
I am trying to create an script to login to my home router and press the button restart.
Running to error, when trying to login to the router, can some on guide on my mistake here.
below is the code and also attaching the .screenshot
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
driver_service = Service(executable_path="C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=driver_service)
PASSWORD = 'testtes'
login_page = 'http://192.168.2.1/login.html'
driver.get(login_page)
driver.find_element_by_xpath("//input[#placeholder='Password']").send_keys(PASSWORD)
Below is the error I am getting.
Traceback (most recent call last):
File "C:\Users\admin\Desktop\pyhton\index.py", line 14, in
driver.find_element_by_xpath("//input[#placeholder='Password']").send_keys(PASSWORD)
AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'
getting this error now.
Traceback (most recent call last):
File "C:\Users\admin\Desktop\pyhton\index.py", line 13, in
driver.find_element(By.XPATH, "//input[#placeholder='Password']").send_keys(PASSWORD)
File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 856, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 429, in execute
self.error_handler.check_response(response)
File "C:\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 243, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[#placeholder='Password']"}
Probably you are using Selenium 4. if so, find_element_by_xpath and all the others find_element_by_* methods are not supported by Selenium 4, you have to use the new syntax and add an essential import, as following:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
driver_service = Service(executable_path="C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=driver_service)
PASSWORD = 'testtes'
login_page = 'http://192.168.2.1/login.html'
driver.get(login_page)
driver.find_element(By.XPATH, "//input[#placeholder='Password']").send_keys(PASSWORD)
Try this:
from selenium.webdriver.common.by import By
driver.find_element(By.XPATH, "//input[#placeholder='Password']").send_keys(PASSWORD)

Message: Unable to locate element, Selenium Python

I'm trying to get access to this page "fullcollege" with a bot I'm making for students. The problem is that I can't even select an element from it, and this error shows up. I have recently tested my code with another webpages like instagram and everything works perfectly. Anyone knows what can I do to solve this? Thanks in advance.
My code:
from time import sleep
from selenium import webdriver
browser = webdriver.Firefox()
browser.implicitly_wait(5)
browser.get('https://www.fullcollege.cl/fullcollege/')
sleep(5)
username_input = browser.find_element_by_xpath("//*[#id='textfield-3610-inputEl']")
password_input = browser.find_element_by_xpath("//*[#id='textfield-3611-inputEl']")
username_input.send_keys("username")
password_input.send_keys("password")
sleep(5)
browser.close()
The error:
Traceback (most recent call last):
File "c:\Users\marti\OneDrive\Escritorio\woo\DiscordBot\BetterCollege\tester.py", line 11, in <module>
username_input = browser.find_element_by_xpath("//*[#id='textfield-3610-inputEl']")
File "C:\Users\marti\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Users\marti\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\marti\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\marti\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[#id='textfield-3610-inputEl']
The username and password field is inside and iframe you need to switch it first.
browser.get('https://www.fullcollege.cl/fullcollege/')
WebDriverWait(browser,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#logFrame")))
sleep(5)
username_input = browser.find_element_by_xpath("//input[#id='textfield-3610-inputEl']")
password_input = browser.find_element_by_xpath("//input[#id='textfield-3611-inputEl']")
username_input.send_keys("username")
password_input.send_keys("password")
import below libraries as well.
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

Super new to python, trying to fill web form and login

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
web = webdriver.Chrome()
web.get('https://id.pcgeducation.com/id093')
time.sleep(4)
user = web.find_element(By.CLASS_NAME,"Name")
user.send_keys("aaaaaa#paaaas.com")
It is giving me the errors
Traceback (most recent call last):
File "C:\Users\Bowie\PycharmProjects\AutomatedFormFilling\main.py", line 10, in <module>
user = web.find_element(By.CLASS_NAME,"Name")
File "C:\Users\Bowie\PycharmProjects\AutomatedFormFilling\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 857, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\Bowie\PycharmProjects\AutomatedFormFilling\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 435, in execute
self.error_handler.check_response(response)
File "C:\Users\Bowie\PycharmProjects\AutomatedFormFilling\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".Name"}
(Session info: chrome=103.0.5060.134)
I really don't know what I am doing wrong with the find element class. Do I not have the correct PIP modules installed?

Python selenium doesn't click

So I'm losing my mind over here. I want to click on a specific button but there is an error which I don't understand:
Traceback (most recent call last):
File "C:\Users\leosc\PycharmProjects\ogameBot\guideline.py", line 22, in guideline
if metalMineLVL() > (10):
File "C:\Users\leosc\PycharmProjects\ogameBot\guideline.py", line 10, in <lambda>
metalMineLVL = lambda: c.metalMine.checkLVL()
File "C:\Users\leosc\PycharmProjects\ogameBot\classes.py", line 121, in checkLVL
a = self.sparte()
File "C:\Users\leosc\PycharmProjects\ogameBot\classes.py", line 54, in <lambda>
(By.XPATH, ('//*[contains(text(),\'{}\')]').format(sparte))))
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\support\wait.py", line 71, in until
value = method(self._driver)
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\support\expected_conditions.py", line 64, in __call__
return _find_element(driver, self.locator)
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\support\expected_conditions.py", line 415, in _find_element
raise e
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\support\expected_conditions.py", line 411, in _find_element
return driver.find_element(*by)
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
from unknown error: web view not found
(Session info: chrome=72.0.3626.121)
(Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.17134 x86_64)
Here the code:
self.sparte = lambda: wait.until(
EC.presence_of_element_located(
(By.XPATH, ('//*[contains(text(),\'{}\')]').format(sparte))))
self.LVL = lambda: int(
wait.until(EC.presence_of_element_located((By.XPATH, ('//*
[#ref=\'' + str(ref) + '\']/span/span')))).text)
def checkLVL(self):
time.sleep(1)
self.sparte().click()
time.sleep(1)
return self.LVL()
metalMineLVL = lambda: c.metalMine.checkLVL()
roboFabLVL = lambda: c.roboFab.checkLVL()
try:
if metalMineLVL() > (10):
if roboFabLVL() <(5):
c.roboFab.build()
except:
pass
When I activate the debugger I see that every thing is processed until it gets to
self.sparte = lambda: wait.until(
EC.presence_of_element_located(
(By.XPATH, ('//*[contains(text(),\'{}\')]').format(sparte))))
and then it goes to the exception part. BUT I use this line of code in the rest of the program all the time and usually it works perfectly. What do I do wrong?
Thanks in advance!!
I don't know why you get that error. My best guess is that it's because of namespace conflicts but I'm not sure. This is the code I use for clicking on things:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
def clickElement(driver, XP):
WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, XP)))
driver.find_element_by_xpath(XP).click()
Example:
clickElement(driver, '/html/body/div[3]/div/a[1]')
Also check out PEP 498 for string formating.
I now found out that the problem was that the program opens 4 additional tabs and then closes the initial one. Normally, I then did:
newTabs = c.driver.window_handles
for tab in newTabs:
c.driver.switch_to.window(tab)
to get Selenium working on the new tabs. Yet, writing the new code, I forgor to do so, so Selenium thought it's still operating on the initial tab, which was already closed.
Thanks a lot anyway!!

Bot selenium, python. time.sleep(n) error

Is there anything better than selenium if I need to parse and click on DOM elements?
An open browser is optional (rather not needed).
Are there any better options for this?
BTW
Why does error appear after this time.sleep(n).
Error:
Traceback (most recent call last):
File "main.py", line 39, in <module>
print("Buy: " + str(elemGreen.text))
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 76, in text
return self._execute(Command.GET_ELEMENT_TEXT)['value']
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=69.0.3497.100)
My Python code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
def loginCheck():
l = driver.find_elements_by_css_selector(".not-login")[0]
if(l.text == "Login or Join Trading"):
return True
else:
return False
driver = webdriver.Chrome(r"C:\Users\Andrew\Desktop\chromedriver.exe")
driver.get("https://abcc.com/markets/ethusdt")
if(loginCheck() == False):
print("Next step")
else:
print("Waiting for the login")
time.sleep(10)
expected_conditions.visibility_of_all_elements_located handles StaleElementReferenceException. You can use it to locate the element
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
def loginCheck():
elements = WebDriverWait(driver, 30).until(expected_conditions.visibility_of_all_elements_located((By.CLASS_NAME, 'not-login')))
l = elements[0]
if (l.text == "Login or Join Trading"):
return True
else:
return False

Categories

Resources