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()
Related
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()
Cant send commands to selenium webdriver in detached session because link http://localhost:port died.
But if i put breakpoint 1 link stay alive
import multiprocessing
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def create_driver_pool(q):
options = Options()
driver = webdriver.Chrome(options=options)
pass #breakpoint 1
return driver.command_executor._url
windows_pool = multiprocessing.Pool(processes=1)
result = windows_pool.map(create_driver_pool, [1])
print(result)
pass # breakpoint 2 for testing link
why is this happening and what can i do about it?
After some research i finally found the reason for this behavor.
Thanks https://bentyeh.github.io/blog/20190527_Python-multiprocessing.html and some googling about signals.
This is not signals at all.
I found this code in selenium.common.service
def __del__(self):
print("del detected")
# `subprocess.Popen` doesn't send signal on `__del__`;
# so we attempt to close the launched process when `__del__`
# is triggered.
try:
self.stop()
except Exception:
pass
This is handler for garbage collector function, that killing subprocess via SIGTERM
self.process.terminate()
self.process.wait()
self.process.kill()
self.process = None
But if you in the debug mode with breakpoint, garbage collector wont collect this object, and del wont start.
Whenever I run the following file (and main encounters the WebDriverException exception) my program ends instead of restarting. Would anyone know why that's happening? Any help would be greatly appreciated – thank you.
from uploadToBeatstars import main
from selenium.common.exceptions import WebDriverException
try:
main()
except WebDriverException:
print("Dumb target error happened. Restarting program.")
from uploadToBeatstars import driver
driver.close()
import sys
import os
os.execv(sys.executable, ['python'] + sys.argv)
You don't need to respawn the interpreter after a failure in general, just retry in a loop:
from uploadToBeatstars import main, driver
from selenium.common.exceptions import WebDriverException
while True:
try:
main()
except WebDriverException:
print("Dumb target error happened. Restarting program.")
driver.close() # Not sure if it is needed, can driver be alive after an exception?
# Try again
else:
break # Stop if no exception occurred.
on windows, the os.exec* family of functions do not operate as they do on posixlikes -- instead of replacing the current process, they spawn a new one in the background and os._exit(1)
more on this here: https://github.com/python/cpython/issues/53394
on Windows, exec() does not really replace the current process. It creates a new process (with a new pid), and exits the current one.
you're probably best to either write a loop or use some sort of process manager
So I've got a selenium python script that occasionally runs into the following error at differing sections in my code:
Exception has occurred: WebDriverException
Message: unknown error: cannot determine loading status
from target frame detached
But when I encounter this error, if I re-run the program without changing anything, everything works again (so I know that it's either a problem with the website or the webdriver). In the meantime, I was wondering if there was a way to tell python to restart the program if a WebDriverException is encountered. Any help would be greatly appreciated, thank you.
You could try os.execv(), according to here, it enables a python script to be restarted, but you need to clean the buffers etc using this C-like function sys.stdout.flush()
try:
<your block of code>
except WebDriverException:
print(<Your Error>)
import os
import sys
sys.stdout.flush()
os.execv(sys.argv[0], sys.argv)
You could simply use the os module to do this: os.execv(sys.argv[0], sys.argv)
Use a main() function as a starting point for your program, and trigger that function again whenever you need to restart. Something like
def foo1():
return
def foo2():
try:
...
except:
main()
def main():
foo1()
foo2()
if __name__ == "main":
main()
If the error occurs because it does not find a certain tag, you could put a wait
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
or worst case
browser.implicitly_wait(5)
or
time.sleep(5)
which waits 5 seconds for the element to appear
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.