Push username & password to alert using Selenium python 3+ - javascript

Alert on website
Hi Everyone
i am trying to accept alert using below code but i am getting timeout exception everytime. tried increasing wait time still same error
wait = WebDriverWait(driver, 60)
driver.get('abc.com')
alert = wait.until(EC.alert_is_present()) ----------Error at this line
time.sleep(4)
#WebDriverWait(driver, 3).until(EC.alert_is_present())
alert = driver.switch_to.alert
alert.send_keys('username' + Keys.TAB + 'password')
alert.accept()
Error :-
Traceback (most recent call last):
File "C:\Users\Gaurav Chhabra\Desktop\FAIL_RATE.py", line 30, in <module>
alert = wait.until(EC.alert_is_present())
File "C:\Users\Gaurav Chhabra\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
What could be the reason as have used the same code on another website and its working, is this is because of some website features which are unable etc ?
i have also attached image of alert
or if somebody can help me with some new way to pass username & password in this alert ?
thanks

Related

Javascript - prompt cause 'document is not focused'

If I add a prompt to the function it works once, but gives the error:
"Uncaught (in promise) DOMException: Document is not focused" at the second attempt.
This is the code:
function site(str) {
var url = prompt();
var text = 'The URL is ';
(async() => {
await navigator.clipboard.writeText(text + url);
})();
}
<button class="button" onclick='site()'>URL</button>
I've asked my best friend, Google, but I can't find any solutions. What am I doing wrong?
It is probably caused by this bug in chromium (Issue #1085949) which makes your prompt call take focus from the Document and not return it when closed. I was not able to reproduce this issue on Safari and Firefox.
The same bug can be reproduced by doing alert instead of prompt followed by navigator.clipboard.writeText.
Your JS may be running on a child page. The following works for me:
await parent.navigator.clipboard.writeText('text to copy to Clipboard here.);
The same error will occur, if you don't await AND immediately after the command e.g. do an alert for feedback to the user, as the alert will steal the focus. Or if you otherwise navigate away or change the focus as a side effect.
(not the case in the above question, but just in case someone else stumbles across this problem and finds this question, I'll leave it here)

Python selenium shows exception

I am getting an exception while trying to open a new link. I have written python script and I expected it will open new link whenever it meets certain condition but while it meet condition it shows alert popup(while entering my credential, it shows exception) and I don't know how to fix it. Currently I am working on Firefox browser and I also checked previous questions related to this issue, where their issue got fixed by changing the browser from Firefox to IE, but in my case I can't use IE since my base link will not open(support) in IE. Is there any way to fix this one?
Here is my code:
import time
from datetime import datetime
from selenium import webdriver
try:
driver = webdriver.Firefox(executable_path="C:\\Users\\Programs\\Python\\Python36\\Lib\\site-packages\\selenium\\webdriver\\firefox\\geckodriver.exe")
driver.get('https://base_link')
my_id = driver.find_element_by_name('j_username')
my_id.send_keys('1895')
password = driver.find_element_by_name('j_password')
password.send_keys('1895')
ext = driver.find_element_by_name('extension_login_user')
ext.send_keys('4081111895')
sign_in_button = driver.find_element_by_id('signin-button')
sign_in_button.click()
time.sleep(30)
driver.set_window_size(1024, 768)
driver.maximize_window()
ticket_opened = False
window = 0
while True:
if driver.find_element_by_id('state-text').text == 'Not Ready - GMC Work':
time.sleep(1)
if driver.find_element_by_id('state-text').text == "Not Ready - Break":
if ticket_opened is False:
driver.execute_script("$(window.open('child_link'))")
driver.switch_to_window(driver.window_handles[window])
window += 1
continue
else:
ticket_opened = False
else:
continue
else:
continue
except Exception as e:
print('Exception Occurred: ' + str(e))
print('Time and Date: ' + str(datetime.now())[0:19])
Here I am getting the exception (output):
Exception Occurred: Alert Text: None
Message:
Time and Date: 2017-10-19 04:13:39
Kindly help me to fix out this one using python selenium. If we can't fix this one, then kindly suggest me some other tool/way to fix this one.

Selenium Python Execute JavaScript click link i get an error. I think my syntax is wrong

I am trying to click a link on our webpage. The page is built from GWT.
I am using the JavaScript execute in Selenium Python.
self.driver.execute_script("document.gElementById('tab_administration').click()")
I get the following error when i run my code:
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: JavaScript error
My code snippet is:
def click_administration(self):
time.sleep(10)
#self.driver.find_element(By.ID, 'tab_administration').click()
self.driver.execute_script("document.gElementById('tab_administration').click()")
#wait = WebDriverWait(self.driver, 10)
#element = wait.until(EC.element_to_be_clickable((By.ID, 'tab_administration')))
#element.click()
return AdministrationPage(self.driver)
Is my JavaScript call syntax incorrect? Why is it failing?
In Firefox dev tools it works. From the console window i enter this line of code:
document.gElementById('tab_administration').click()";
I am trying driver.execute_script because when i try WebDriverWait(self.driver, 10) i get a TimeOut Exception.
Some help appreciated. Thanks.
Riaz
try this:
self.driver.execute_script("arguments[0].click()", yourElement);

Firefox hang on jQuery based site after loading halfway when automating Selenium using Python

I'm trying to scrape a site that's jQuery based and I'm having trouble with getting the page to load completely before extracting the elements with Selenium. The page has multiple modules, each of which is a different query. I tried using the wait commands I found in the documentation, but it would usually hang the browser after one of the multiple queries load.
For reference, my OS is Windows 7, Firefox 30.0, Python 2.7 and Selenium 2.42.1
The commands and results I tried are as follows:
Explicit Wait: Browser hangs after loading the first query (Firefox Not Responding)
try:
element = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, path)))
finally:
browser.quit()
Expected Conditions: Browser hangs after loading the first query (Firefox Not Responding)
wait = WebDriverWait(browser, 10)
element = wait.until(EC.element_to_be_clickable((By.XPATH,path)))
Implicit Wait: Firefox hangs after loading the first query (Firefox Not Responding)
browser.implicitly_wait(10) # seconds
myDynamicElement = browser.find_element_by_xpath(path)
Custom Function: Page loads, but selenium starts scraping before the second query is loaded resulting in an error
def wait_for_condition(browser,c):
for x in range(1,10):
print "Waiting for jquery: " + c
x = browser.execute_script("return " + c)
if(x):
return
time.sleep(1)
def main():
wait_for_condition(browser,"jQuery.active == 0")
#First element to be clicked on to scrape:
path="//a[starts-with(#class, 'export db')]"
browser.find_element_by_xpath(path).click()
The error is:
selenium.common.exceptions.NoSuchElementException: Message: u'Unable to locate element: {"method":"xpath","selector":"//a[starts-with(#class, \'export db\')]"}' ;
Catching this exception and running wait_for_condition again in the except block causes the browser to stop loading the rest of the queries and hang:
wait_for_condition(browser,"jQuery.active == 0")
try:
path="//a[starts-with(#class, 'export db')]"
browser.find_element_by_xpath(path).click()
except NoSuchElementException:
wait_for_condition(browser,"jQuery.active == 0")
path="//a[starts-with(#class, 'export db')]"
browser.find_element_by_xpath(path).click()
Please let me know if you have any suggestions to solving the problems.
Thanks in advance,
Teresa

Testing and editing JavaScript (both standalone and in HTML) in SciTE?

Whenever I try to run a '.js' file in SciTE (Scintilla Text Editor) I almost always get an error stating that certain variables are undefined. I'm guessing that SciTE doesn't have many JavaScript libraries, but I'm not sure.
A few searches yielded me these two blog posts on how to get SciTE to print JavaScript test to its output, rather than just opening a web browser when you press F5 to test the code.
I tried them both, but I either got the same errors as before with the first post's solution, or I got an error that said "'jrunscript' is not recognized as an internal or external command, operable program or batch file" with the second method.
So, is it possible to test JavaScript code in SciTE and print the JavaScript output (or errors) to SciTE's output?
Simple example code I've tried:
console.log("test")
The error message I received for this: 'Microsoft JScript runtime error: 'console' is undefined'
What is SciTe?
SciTE is a SCIntilla based Text Editor. Lua is embedded with SciTe which allows you to access the Scintilla API.
# lua code example
`command.go.*.js=jrunscript $(FileNameExt)`
How to run js code in SciTe?
Create a file called testConsole.js with the following content.
var console = console || {};
console.log = ( console.log || function( str ){
if( typeof print == "function" ){
print( "LOG: " + str + "\n" );
}
return "LOG: " + str;
});
console.log( "Javascript works." );
Open testConsole.js in SciTe.
To run the code, press F5 or click Tools > Go.
An output window should appear showing
LOG: Javascript works.
How do I configure SciTe to run javascript?
I'm using SciTe 3.2.0. Located here
In wscite\wsite320\cpp.properties at line: 424
change:
command.go.*.js=cscript /nologo $(FileNameExt)
to:
command.go.*.js=jrunscript $(FileNameExt)
if you want to use node.js, then change it to
command.go.*.js=node $(FileNameExt)
Make sure that you have the jrunscript or node in your path for the environment variables.
Tutorial here
Do I have jrunscript?
Here's the easiest way to check.
Open up run > type in cmd > type jrunscript.
js> should appear on the screen.
jrunscript.exe should be located here.
C:\Program Files\Java\jdk1.7.0_01\bin\jrunscript.exe
Download the lastest Java SDK if you can't find it.
Error Messages
What does 'Microsoft JScript runtime error: 'console' is undefined'
This means Microsoft JScript ran your javascript and couldn't find the variable console.
Define console to get rid of the error message.
var console = console || {};
console.log = ( console.log || function( str ){
if( typeof print == "function" ){
print( "LOG: " + str + "\n" );
}
return "LOG: " + str;
});
Microsoft JScript might be located here:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\jsc.exe
Error: Input Error: There is no file extension in "location"
Solution: You need to configure the cpp.properties file for javascript.
Error: script file test is not found
Solution: Rename the file. Make sure that it doesn't have any spaces.

Categories

Resources