Python selenium doesn't click - python

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

Related

Selenium WebDriver.wait does not wait Python

I want to have Selenium wait until a webpage is loaded. I use Safari 14.1.2 on macOS 10.15.7
So I tried as below:
// login process and it successes and the following page shows up
login_submit.click()
// the page after the authorization, make selenium wait until ```hoge``` is clickable
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'hoge')))
This code does not work as expected. It fails with an error selenium.common.exceptions.NoSuchFrameException:. The error comes immediately, which seems there is no 10 s wait.
The stack trace is as below: (Paths are modified.)
Traceback (most recent call last):
File "/login.py", line 99, in <module>
login_schedule().quit()
File "/login.py", line 67, in login_schedule
wait.until(EC.presence_of_element_located((By.ID, 'HOGEHOGE')))
File "/selenium/webdriver/support/wait.py", line 71, in until
value = method(self._driver)
File "/selenium/webdriver/support/expected_conditions.py", line 64, in __call__
return _find_element(driver, self.locator)
File "/selenium/webdriver/support/expected_conditions.py", line 415, in _find_element
raise e
File "/selenium/webdriver/support/expected_conditions.py", line 411, in _find_element
return driver.find_element(*by)
File "/selenium/webdriver/remote/webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchFrameException: Message:
When I put time.sleep(10) instead as below,
import time
// login process and it successes and the following page shows up
login_submit.click()
time.sleep(10)
// the page after the authorization, make selenium wait until ```hoge``` is clickable
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'hoge')))
it works as expected.
Note that the last part can even be replaced
browser.find_element_by_xpath("//select[#id='hoge']")
What is wrong with my Python code?
try to use this function to wait until the element or something appears:
def wait_for(xpath):
while True:
try:
driver.find_element_by_xpath(xpath)
return True
except NoSuchElementException:
continue
do not forget
from selenium.common.exceptions import NoSuchElementException
you can use anything it is not important to be XPATH as a method.

python with selenium automating login

I'm new to selenium
Here I want to ask about a problem code (actually not mine)
this is the code
aww = email.strip().split('|')
driver = webdriver.Chrome()
driver.get("https://stackoverflow.com/users/signup?ssrc=head&returnurl=%2fusers%2fstory%2fcurrent")
time.sleep(5)
loginform = driver.find_element_by_xpath("//button[#data-provider='google']")
loginform.click()
mailform = driver.find_element_by_id('identifierId')
mailform.send_keys(aww[0])
driver.find_element_by_xpath("//div[#id='identifierNext']").click()
time.sleep(3)
passform = driver.find_element_by_css_selector("input[type='password']")
passform.send_keys(aww[1])
driver.find_element_by_id('passwordNext').click()
time.sleep(3)
driver.get("https://myaccount.google.com/lesssecureapps?pli=1")
open('LIVE.txt', 'a+').write(f"CHECKED : {aww[0]}|{aww[1]}")
time.sleep(3)
lessoff = driver.find_element_by_xpath('//div[#class="hyMrOd "]/div/div/div//div[#class="N9Ni5"]').click()
driver.delete_all_cookies()
driver.close()
I'm using those code for automating turn on the less-secure apps from Gmail
and the error will pop up like this
quote Traceback (most recent call last):
File "C:\Users\ASUS\Downloads\ok\less.py", line 59, in
lessoff = driver.find_element_by_xpath('//div[#class="hyMrOd "]/div/div/div//div[#class="N9Ni5"]').click()
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\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\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#class="hyMrOd "]/div/div/div//div[#class="N9Ni5"]"}
(Session info: chrome=86.0.4240.183)
any help gonna be helpfull,sorry for my english before :)
You can simply target this xpath and .click to toggle the less secure apps.
lessoff = driver.find_element_by_xpath("input[type='checkbox']").click()
It looks like it couldn't find the element it's looking for so give some time to load the element. You can check with Wait().until.
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, 'YOUR_XPATH')))
when you try to click an element make sure it's there. above code will wait until the element located for the 10s if the element not located then it will throw an exception

I am trying to automate opening charts in Tradingview using Selenium with Python

from selenium import webdriver
import time
DRIVER = 'chromedriver'
driver = webdriver.Chrome(DRIVER)
driver.get("https://www.tradingview.com/#signin")
driver.find_element_by_name("username").send_keys("Username")
driver.find_element_by_name("password").send_keys("Password")
driver.find_element_by_xpath("//button[#type='submit']").click()
driver.maximize_window()
driver.find_element_by_link_text('Chart').click()
driver.find_element_by_class_name('input-3lfOzLDc').send_keys('SBIN')
time.sleep(20)
driver.quit()
Everything is working fine here but when I try to find element which needs to be change( the one sending SBIN , I get this error
Traceback (most recent call last):
File "tview.py", line 11, in <module>
driver.find_element_by_xpath("//input[#class='input-3lfOzLDc']").send_keys('SBIN')
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, 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[#class='input-3lfOzLDc']"}
Can someone please help out
waiting a little bit longer works fine. I imported keys too because you had to clear that textbox
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
DRIVER = 'chromedriver'
driver = webdriver.Chrome(DRIVER)
driver.get("https://www.tradingview.com/#signin")
driver.find_element_by_name("username").send_keys("sibyl666")
driver.find_element_by_name("password").send_keys("417305628m")
driver.find_element_by_xpath("//button[#type='submit']").click()
driver.maximize_window()
driver.find_element_by_link_text('Chart').click()
time.sleep(5)
driver.find_element_by_class_name('input-3lfOzLDc').send_keys(Keys.CONTROL + "a")
driver.find_element_by_class_name('input-3lfOzLDc').send_keys(Keys.DELETE);
driver.find_element_by_class_name('input-3lfOzLDc').send_keys('SBIN')
time.sleep(20)
driver.quit()
this may be too late, but here it is what works for me. Basically, I use .clear() to get rid of the previous value and add some waiting times (depends on how fast the website loads on your machine).
ticker = driver.find_element_by_class_name('input-3lfOzLDc')
time.sleep(2)
ticker.clear()
time.sleep(2)
ticker.send_keys('SBIN')
time.sleep(2)
ticker.send_keys(Keys.RETURN)

Upload file with Selenium Webdriver Python

I have tried the method from this page:
Upload file with Selenium in Python
Code:
file_button = browser.find_element_by_id('fileUploadProxy')
file_button.send_keys('/Users/home/Downloads/1-Students-and-Parent-Email.csv')
But I get the following error:
Traceback (most recent call last):
File "test.py", line 110, in <module>
upload_students_results('Surname, Name')
File "test.py", line 91, in upload_students_results
file_button.send_keys('/Users/home/Downloads/1-Students-and-Parent-Email.csv')
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py", line 349, in send_keys
'value': keys_to_typing(value)})
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py", line 493, in _execute
return self._parent.execute(command, params)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 249, in execute
self.error_handler.check_response(response)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 193, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element
(Session info: chrome=58.0.3029.96)
(Driver info: chromedriver=2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.4 x86_64)
The problem is - you are sending keys to the div element which is not "interactable", does not accept the keys - hence the "cannot focus element" error.
The idea behind the solution you've linked is to send keys to the input element with type="file" that is responsible for the file upload. Find this element in your HTML and send keys to it.
Note that this element could be invisible. In this case, you should first make it visible for the send_keys() to work.
Update:
Okay, now we at least know which element is our desired one:
<input type="file" name="fileToUpload" id="fileToUpload2" class="fileToUpload">
Since you have troubles locating this element, either try waiting for it:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
file_upload = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "fileToUpload2"))
)
file_upload.send_keys('/Users/home/Downloads/1-Students-and-Parent-Email.csv')
Or/and, check if this element is inside an iframe - if it is, you would need to switch into the context of the iframe and only then perform the element search.
I had the same problem when I inserted the file path as a string. This is functional:file_input.send_keys(os.path.abspath("path/to/the/file.xyz"))

Python Selenium stale element exception

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.

Categories

Resources