Selenium Webdriver python showing error soon after it executes the code - python

When I run my python script which is supposed to open github in edge browser, it works, but closes soon after it is done
#imports
from selenium import webdriver
from selenium.webdriver.edge.service import Service
# Change the directory
#Github
def github():
browser = webdriver.Edge(r'C:\Program Files\Browser Drivers\Edge Drivers\msedgedriver.exe')
browser.get("https://github.com")
if __name__ == "__main__":
github()
The error
DevTools listening on ws://127.0.0.1:52908/devtools/browser/7ebfcee1-74f9-43ba-bf79-
99549f4d7ccf
[2916:7184:0428/150623.910:ERROR:fallback_task_provider.cc(124)] Every renderer should have at
least one task provided by a primary task provider. If a "Renderer" fallback task is shown, it
is a bug. If you have repro steps, please file a new bug and tag it as a dependency of
crbug.com/739782.

Related

SendMouseWheelEvent does not work on subsequent page loads

I'm trying to use SendMouseWheelEvent to pass mouse scrolls into the browser, but it is only working on the first page load. Any subsequent pageloads after that, it does not work, unless the browser is interferred with actual mouse scroll.
I've prepared the following script. The "errorrep" is actually the name of the script itself, as "errorrep.py", into which I'm assigning the browser as "mybrowser".
How can I have the browser correctly work with SendMouseWheelEvent on subsequent pageloads?
cefpython version is 66.1.
"""
SendMouseWheelEvent is correctly performed on the first page load. On any pageloads after that, it does not seem to work, but it works again when the actual mouse device performs a scroll on the webpage
'# test 1' which does a javascript code 'scrollBy', works on every pageload.
'# test 2' which does a SendMouseWheelEvent, only works on first page load.
"""
from cefpython3 import cefpython as cef
import time
from threading import Thread
import errorrep
mybrowser = None
def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url="https://stackoverflow.com/")
browser.SetClientHandler(LoadHandler())
errorrep.mybrowser = browser
cef.MessageLoop()
del browser
cef.Shutdown()
class LoadHandler(object):
def OnLoadingStateChange(self, browser, is_loading, **_):
if not is_loading:
Thread(target=test).start()
def test():
print("Page loading is complete!")
for i in range(5):
print('scrolling')
# test 1
errorrep.mybrowser.ExecuteJavascript(jsCode="""scrollBy(0,25)""")
# test 2
# errorrep.mybrowser.SendMouseWheelEvent(0,0,0,-120, cef.EVENTFLAG_NONE)
time.sleep(1)
print('opening new page, clicking on the logo link')
errorrep.mybrowser.ExecuteJavascript(jsCode="""document.getElementsByClassName('s-topbar--logo js-gps-track')[0].click();""")
if __name__ == '__main__':
main()

How can I use psutil to constantly check if a process/application is running?

I tried using the answer in Python check if a process is running or not to help me. However, when I tried to implement psutil into my code it did not work successfully.
I created a GUI using tkinter and I am trying to make it so as soon as the application opens, the application will be moved to the selected location. Am I using psutil incorrectly?
Here's a portion of my code:
if clicked1.get() == "Google Chrome"
os.startfile(r"{google chrome file location}")
time.sleep(4) # time.sleep to allow the application time to open
app.connect(path=r"{google chrome file location}")
app1 = app.top_window()
app1.move_window(-20, -2150) # moves application to those x and y coordinates
time.sleep(.5) # gives the application time to move before maximizing
app1.maximize()
Here's my code when I tried to implement psutil:
if clicked1.get() == "Google Chrome"
os.startfile(r"{google chrome file location}")
while True:
if "Google Chrome" in (p.name() for p in psutil.process_iter()
app.connect(path=r"{google chrome file location}")
app1 = app.top_window()
app1.move_window(-20, -2150) # moves application to those x and y coordinates
time.sleep(.5) # gives the application time to move before maximizing
app1.maximize()
break # breaks from the loop when the application is started and is moved

Python process locks main program

So, I create a small program that uses flask to receive some requests and do a few things over selenium. All bits that deal with selenium are in another file that I tried to run first using a thread, and when it did not worked, a process. I believe that the problem is because I use a while true to keep my selenium working. The selenium part knows what to do because it keep checking the variable that I update from them flask part...
This is pretty much my main class that runs the selenium and them start flask, but it never start flask. It get locked on the .start().
if __name__ == "__main__":
# Logging
log_format = '%(asctime)s [%(filename)s:%(lineno)d] %(message)s'
logging.basicConfig(format=log_format,
level=logging.INFO,
stream=sys.stdout)
# Start Selenium
browser = Process(target=selenium_file.run_stuff())
browser.start()
print('TEST')
# Flask
app.run(debug=True)
Not really sure how I could solve this problem (if it's a problem)...
Exchange browser = Process(target=selenium_file.run_stuff()) with browser = Process(target=selenium_file.run_stuff)
You don't pass the function run_stuff but you already execute it and hence it blocks your program until run_stuff returns.

Pycharm,Selenium Process finished with exit code zero [duplicate]

This question already has an answer here:
Selenium with Python-unittest - Test returns Process finished with exit code 0 and no action is performed
(1 answer)
Closed 3 years ago.
When i'am trying to run my code though Pycharm it doesnt execute anything. Normally it should run code and Chrome should start.
1) Tried to run from Terminal still the same.
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
import time
import unittest
class SearchText(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.get('http://book.theautomatedtester.co.uk/')
self.driver.maximize_window()
time.sleep(2)
self.driver.switch_to_window(driver.window_handles[0])
def test_search_by_text(self):
self.driver.find_element_by_xpath('/html/body/div[2]/ul/li[1]/a').click()
self.driver.find_element_by_id('radiobutton').click()
self.driver.find_element_by_id('selecttype').send_keys('Selenium Code',Keys.ENTER)
self.driver.find_element_by_name('selected(1234)').click()
self.driver.find_element_by_id('storeinput').send_keys('Salamlar')
self.driver.find_element_by_id('secondajaxbutton').click()
self.driver.find_element_by_id('multiplewindow').click()
self.driver.switch_to_window(driver.window_handles[1])
self.driver.find_element_by_id('closepopup').click()
self.driver.switch_to_window(driver.window_handles[0])
self.driver.find_element_by_id('loadajax').click()
self.driver.find_element_by_id('ajaxdiv')
assert driver.page_source.find('The following text has been loaded from another page on this site. It has been loaded in')
aka = driver.find_element_by_id('verifybutton')
if aka.is_enabled():
aka.click()
else: print('Not Existing')
def tearDown(self):
# close the browser window
self.driver.quit()
Expected Result: Code will trigger Browser and will run test
Your code does not actually execute anything.
If you want to execute the unittest you have to call unittest.main(). And since this should only be done when executing the file itself, you should add this at the bottom of your file.
if __name__ == '__main__':
unittest.main()

Waiting for user input when controlling 3rd party application via python script

I am writing a script intended to be used by members of a project team. As part of the script, I am launching a 3rd party proprietary application run through Citrix. I am going to use the script mostly to send keys to this application, but the first step once it launches is for the user to log in.
Because I would like the user to log in while the script is running, rather than asking for user/pass from some kind of GUI input earlier, and because the time it takes Citrix to launch varies, I would like to include some kind of logic that detects when the user has logged in and then resume the script from there, rather than including an obnoxiously long implicit wait or risking the script timing out.
Is there a way to detect user keystrokes using win32com.client (or to detect a change in state of the application itself)? See below for the relevant code to launch the app:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run('C:\Citrix\[rest of path])
EDIT:
Per Vasily's suggestion in the comments below, I attempted to adapt the "hook and listen" code to my scenario, but was unsuccessful. When I launch my file, I don't even get an exception message in my terminal, I get a Windows pop-up that says Python encountered a problem and needs to quit.
This is how I adapted it:
#[omitting import lines for brevity]
def on_timer():
"""Callback by timer out"""
win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);
def on_event(args):
"""Callback for keyboard and mouse events"""
if isinstance(args, KeyboardEvent):
for i in range(1,100):
time.sleep(1)
if args.pressed_key == 'Lcontrol':
break
def init():
hk = Hook()
hk.handler = on_event
main_thread_id = win32api.GetCurrentThreadId()
t = Timer(55.0, on_timer) # Quit after 55 seconds
t.start()
hk.hook(keyboard=True, mouse=True)
At the point when the 3rd party Citrix app begins to launch in my main script, I call hookandlisten.init().
As a reminder, my goal is to wait until the user sends a certain keystroke (here I chose Control) before proceeding with the rest of the main script.
Solved this by eliminating the timer and unhooking the keyboard upon the correct keystroke:
import win32api
import win32con
from pywinauto.win32_hooks import Hook
from pywinauto.win32_hooks import KeyboardEvent
from pywinauto.win32_hooks import MouseEvent
def on_event(args):
"""Callback for keyboard and mouse events"""
if isinstance(args, KeyboardEvent):
if args.current_key == 'Lcontrol' and args.event_type == 'key down':
print("Success")
hk.unhook_keyboard()
return
def init():
hk.handler = on_event
hk.hook(keyboard=True, mouse=False)
hk = Hook()

Categories