I am trying to build a bot and that needs to be able to interact with permission boxes. This bot is supposed to click accept/dismiss depending on what the user input; however, every time I attempt to interact with the permissions popup that appears in the html file I get the error mentioned below. I have lightly looked into the Alert object, and I have tried driver.switch_to_alert(), but, I find that that has been deprecated. I running the latest version of python, and the the latest version of selenium, along with the latest version of the chrome driver. The error message below, is the same message I get for all methods I have attempted to use to solve this problem.
driver.switch_to_alert()
Traceback (most recent call last):
File "C:/Users/micha/PycharmProjects/botty/alert_testing.py", line 9, in <module>
driver.switch_to_alert()
File "C:\Users\micha\.virtualenvs\botty-KuDX6gMP\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 803, in switch_to_alert
return self._switch_to.alert
File "C:\Users\micha\.virtualenvs\botty-KuDX6gMP\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 55, in alert
alert.text
File "C:\Users\micha\.virtualenvs\botty-KuDX6gMP\lib\site-packages\selenium\webdriver\common\alert.py", line 67, in text
return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"]
File "C:\Users\micha\.virtualenvs\botty-KuDX6gMP\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\micha\.virtualenvs\botty-KuDX6gMP\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoAlertPresentException: Message: no such alert
(Session info: chrome=86.0.4240.111)
Process finished with exit code 1
My code:
from selenium.webdriver import Chrome
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.alert import Command
from time import sleep
driver = Chrome()
driver.get('file:///C:/Users/micha/Scripts/web%20design/javaScriptTesting/jscriptTesting.html')
sleep(3)
al = driver.switch_to.alert
al.accept()
input()
Related
This is my first post here!
I am using Selenium's Chrome Driver to send WhatsApp attachment to some people.
Here is my code:
from selenium import webdriver
import os
from time import sleep
link="https://wa.me/91xxxxxxxxxx"
phnno="91xxxxxxxxxx"
driver=webdriver.Chrome(executable_path=f"{os.getcwd()}\\chromedriver.exe")
#driver.get(link)
#button=driver.find_element_by_xpath('//a[#title="Share on WhatsApp"]')
#button.click()
driver.get(f"https://web.whatsapp.com/send?phone={phnno}&text&app_absent=0")
#This above line opens up the sender window in whatsapp
attachbutt=driver.find_element_by_xpath('//span[#data-icon="clip"]') #This is line 15
#The above line is the one that is giving me the error
attachbutt.click()
sleep(10)
forpdf=driver.find_element_by_xpath('//input[#accept="*"]')
path="C:\\Users\\Deven\\Desktop\\test_file.pdf"
forpdf.send_keys(path) #Attaches the file
sleep(5)
sendbutt=driver.find_element_by_xpath('//span[#data-icon="send"]')
sendbutt.click()
ERROR:
DevTools listening on ws://127.0.0.1:56230/devtools/browser/1a8a2adb-37ee-4b0c-bedc-5cfb58559c24
Traceback (most recent call last):
File "d:\Coding\Python Scripts\Dr Nikhil Prescription App\Prescription Generator\WA-testing.py", line 15, in <module>
attachbutt=driver.find_element_by_xpath('//span[#data-icon="clip"]')
File "C:\Users\Deven\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\Deven\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\Deven\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\Deven\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":"//span[#data-icon="clip"]"}
(Session info: chrome=90.0.4430.212)
PS D:\Coding\Python Scripts\Dr Nikhil Prescription App\Prescription Generator> [16176:15752:0523/212201.236:ERROR:device_event_log_impl.cc(214)] [21:22:01.236] USB: usb_device_handle_win.cc:1054 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
It says it is unable to locate the element but I have bene very careful in inspecting the website and then writing the code. Still I wonder why it does not work. Can anyone please help me with what is it that I am doing wrnong? Thank You!
Looks like you are missing a wait / delay before clicking that element.
The simplest solution is to put
sleep(5)
before
attachbutt=driver.find_element_by_xpath('//span[#data-icon="clip"]')
However, it's much better to use expected conditions there. Like this:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
attachbutt = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, '//span[#data-icon="clip"]')))
I am using selenium to automate some work that I do in Google Analytics. The program was working fine for months until a few days back.
It first logs into google and then opens the relevant analytics pages and gets the required information.
The logging in process works fine and it opens the first analytics page and saves all the info.
Then when I make it move to another page by using the get function, the page loads in a few seconds but the program gets stuck and throws a timeout error after a few mins.
This is the part of the code that gets stuck:
## Getting GEOLOCATIONS
print("Getting GeoLocations")
driver.get("{}{}/{}".format(geourl, key[i], geo[i]))
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((
By.XPATH,"//*[#id=\"ID-reportHeader-reportToolbar"]/div[1]/div[2]/span[2]"
)))
The code gets stuck in the get() function. This is the error after a few mins:
Getting GeoLocations
Traceback (most recent call last):
File "seo.py", line 122, in <module>
driver.get("{}{}/{}".format(geourl, key[i], geo[i]))
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 248, in get
self.execute(Command.GET, {'url': url})
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: timeout
(Session info: chrome=64.0.3282.140)
(Driver info: chromedriver=2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881),platform=Linux 4.4.0-112-generic x86_64)
I am using the latest chromedriver 2.35 and selenium version 3.90.
I'm using Selenium (with python) to monitor a page periodically and save screenshots. This is done on a raspberry pi (armv6). Because of this, I'm using PhantomJS.
I'm monitoring certain elements, and since a raspberry pi isn't the fastest, I am executing a script with driver.execute_script to make the page smaller so that the screenshots aren't too big.
Unfortunately, when executing this script, the following error is thrown:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "`**path**`/bot.py", line 39, in __init__
self.graphs(self.threads['graphs'])
File "`**path**`/bot.py", line 93, in graphs
self.driver.execute_script(`**script**`)
File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 543, in execute_script
'args': converted_args})['value']
File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute
self.error_handler.check_response(response)
File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: {"errorMessage":"Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: \"script-src 'self' *.google-analytics.com\".\n","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"716","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:46451","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"script\": `**script**`, \"args\": [], \"sessionId\": \"69182660-cd69-11e7-b52d-9131a53fa749\"}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/69182660-cd69-11e7-b52d-9131a53fa749/execute"}}
Screenshot: available via screen
I've googled this error but I haven't been able to find a solution. Is this Selenium that's preventing me from executing this script or is a PhantomJS?
Thanks!
[edit]
Here's the code that's initializing the selenium webdriver:
def __init__(self):
self.driver = webdriver.PhantomJS(desired_capabilities=dcap, service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any', '--web-security=false'])
self.driver.set_window_size(1070, 800)
self.threads = {'check_login': threading.Event(), 'graphs': threading.Event()}
self.login()
self.graphs(self.threads['graphs'])
self.check_login(self.threads['check_login'])
I am trying to track down an error in Python Selenium. The error message is..
Traceback (most recent call last):
File "C:\myscipt\main.py", line 110, in <module>
source_mysource(func1, func2, func3, func4, func5, func6, func7, func8, func9)
File "C:\myscipt\sources\functions.py", line 132, in source_mysource
current_url = driver.current_url
File "C:\Users\tom\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 454, in current_url
return self.execute(Command.GET_CURRENT_URL)['value']
File "C:\Users\tom\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "C:\Users\tom\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 193, in check_response
raise exception_class(message, screen, stacktrace, value['alert'].get('text'))
selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier.
<super: <class 'WebDriverException'>, <UnexpectedAlertPresentException object>>
Is the error saying that the line current_url = driver.current_url is the one that is triggering the error or is it the next line?
When you use .current_url property of a WebDriver instance, a GET_CURRENT_URL webdriver command is sent, which is triggering an error in your case. What happens is, the currently opened web-page is not the current top-level browsing context because of the alert being present, and, according to the specification, it should and fails with an error.
In other words, current URL cannot be retrieved when there is an opened active alert.
I'm using webdriver to click on a submit button on a form in an iframe. Basically:
self.driver.find_element_by_css_selector("[name~='field_1']").clear()
self.driver.find_element_by_css_selector("[name~='field_1']").send_keys("123")
self.driver.find_element_by_css_selector("[name~='field_1']").send_keys(Keys.RETURN)
self.driver.switch_to_window(self.driver.window_handles[-1])
self.assertEqual(self.driver.current_url, "http://fake_address.com")
I've also tried:
self.driver.find_element_by_css_selector("[name~='field_1']").clear()
self.driver.find_element_by_css_selector("[name~='field_1']").send_keys("123")
self.driver.find_element_by_css_selector("#submit-endslide").click()
self.driver.switch_to_window(self.driver.window_handles[-1])
self.assertEqual(self.driver.current_url, "http://fake_address.com")
and:
self.driver.find_element_by_css_selector("[name~='field_1']").clear()
self.driver.find_element_by_css_selector("[name~='field_1']").send_keys("123")
self.driver.find_element_by_css_selector("#submit-endslide").submit()
self.driver.switch_to_window(self.driver.window_handles[-1])
self.assertEqual(self.driver.current_url, "http://fake_address.com")
I've been getting:
Traceback (most recent call last):
File "test_ytplayer_smoke_form.py", line 198, in testSmallFormSubmission
self.driver.find_element_by_css_selector("[name~='field_1']").send_keys(Keys.RETURN)
File "/home/giant/our_player/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 293, in send_keys
self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing})
File "/home/giant/our_player/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 370, in _execute
return self._parent.execute(command, params)
File "/home/giant/our_player/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 166, in execute
self.error_handler.check_response(response)
File "/home/giant/our_player/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 164, in check_response
raise exception_class(message, screen, stacktrace)
TimeoutException: Message: u'Selenium took too long to run your command.
Then
WebDriverException: Message: u'Due to a previous error, this job has already finished.
Regardless of which method I choose, I will always get a timeout when clicking the submit button;
(I've already tried increasing the timeout to 300)
Note:When I watch the test run, the submit button is being clicked and a new tab will open, but the test will never pass due to the exceptions.
There seemed to be a browser specific issue Chrome V28 that was causing this issue; I updated to the latest browser version Chrome V35 and this seemed to be resolved
As my comment says, we need more info, but comments are ugly to edit, so I add more info here:
Instead of wait based on time, try WebDriverWait see here for start.
Store element in variable when found, like:
field_1 = self.driver.find_element_by_css_selector("[name~='field_1']")
field_1.clear()
field_1.send_keys("123")
submit = self.driver.find_element_by_css_selector("#submit-endslide")
submit.click()
But try to use WebElementDrive and ExpectedConditions instead of driver methods directly.