In a simple python test that uses the pytest-selenium plugin, I'm getting the following error:
WebDriverException: Message: Service wires unexpectedly exited. Status code was: 1
The test is this:
def test_javascript_loads(selenium):
# Note selenium is a pytest fixture from pytest-selenium
selenium.get(BASE_URL)
wait = WebDriverWait(selenium, MAX_LOAD_TIME)
try:
element = wait.until(EC.title_contains('Project'))
except TimeoutException as e:
assert False
And it's invoked like this:
py.test tests/tests.py -s --driver Firefox --capability marionette 1 --capability binary /Applications/Firefox.app/Contents/MacOS/firefox-bin
Also, I've downloaded the latest release of geckodriver, put it in my path, and renamed it to wires.
What am I doing wrong, and how can I fix it?
Related
I'm using python+selenium, with profile that has addons.
On startup it shows them all momentarily, but then they are concealed. They exist, they are not disabled, but invisible and don't work. I can disable and enable it, then it appears on the taskbar and is functional.
When invoking firefox manually with the profile, it works.
Here's what printed to the log.
1596129664500 mozrunner::runner INFO Running command: "/usr/bin/firefox" "-marionette" "-foreground" "-no-remote" "-profile" "/tmp/rust_mozprofileO34n0s"
JavaScript error: resource:///modules/sessionstore/SessionStore.jsm, line 1325: uncaught exception: 2147746065
JavaScript error: resource://gre/modules/ExtensionContent.jsm, line 554: TypeError: Argument 1 of PrecompiledScript.executeInGlobal is not an object.
1596129672037 Marionette INFO Listening on port 41285
1596129672136 Marionette WARN TLS certificate errors will be ignored for this session
JavaScript error: undefined, line 14: Error: An unexpected error occurred
JavaScript error: moz-extension://45aaa1ae-14fe-4a8f-841d-6a9416fd5d09/lib/picture_in_picture_overrides.js, line 15: Error: Incorrect argument types for pictureInPictureParent.setOverrides.
1596129683512 Marionette INFO Stopped listening on port 41285
Can it be because of these errors?
The code itself is of no interest at all:
#!/usr/bin/env python
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
profile_path='./profile'
opts=Options()
opts.profile=profile_path
driver=Firefox(options=opts)
breakpoint()
Versions are probably more important:
Mozilla Firefox 68.9.0esr
geckodriver 0.26.0 (e9783a644016 2019-10-10
13:38 +0000)
I'm creating an empty directory, then running firefox --new-instance --profile ./profile, then installing addon manually into the profile. But here there is that profile
In your profile there is a file: prefs.js which contains a line user_pref("extensions.lastAppBuildId", "20200707180101"); this line might be at fault for the disabled addons. You could therefore test to decrease this number by 1 or remove the whole line (untested).
profile.set_preference("extensions.lastAppBuildId", "<apppID> -1 ")
Full example code:
from selenium.webdriver import FirefoxProfile
from selenium import webdriver
path = '%APPDATA%\Mozilla\Firefox\Profiles\azk4wioue.default' #path to your profile
profile = FirefoxProfile(path)
profile.set_preference("extensions.lastAppBuildId", "<apppID> -1 ")
driver = webdriver.Firefox(profile)
Example to use an existing firefox profile:
# go to the the following folder %APPDATA%\Mozilla\Firefox\Profiles\
# there the firefox profiles should be stored, the default one ending with .default
# now provide the profile to the driver like this:
profile = FirefoxProfile('%APPDATA%\Mozilla\Firefox\Profiles\azk4wioue.default')
driver = webdriver.Firefox(firefox_profile=profile)
Alternatively install the addon clean on each run through a temporary profile.
# go to https://addons.mozilla.org and search for the plugin you want, e.g.:https://addons.mozilla.org/en-US/firefox/addon/ublock-origin/
# rightclick on the button "add to firefox"
# download the target file to a folder of your choice
# then include the addon like this:
driver.install_addon('/Users/someuser/app/extension.xpi', temporary=True)
Alternatively 2, you can try setting the extension this way:
from selenium.webdriver import FirefoxProfile
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.add_extension(extension='/Users/someuser/app/extension.xpi')
driver = webdriver.Firefox(profile)
If the addons are there after loading the profile but disabled, you can also try this:
def newTab(fx, url="about:blank"):
wnd = fx.execute(selenium.webdriver.common.action_chains.Command.NEW_WINDOW)
handle = wnd["value"]["handle"]
fx.switch_to.window(handle)
fx.get(url) # changes handle
return fx.current_window_handle
def retoggleAllTheAddons(fx):
initialHandlesCount = len(fx.window_handles)
addonsTabHandle = newTab(fx, "about:addons")
fx.execute_script("""
let hb = document.getElementById("html-view-browser");
let al = hb.contentWindow.window.document.getElementsByTagName("addon-list")[0];
let cards = al.getElementsByTagName("addon-card");
for(let card of cards){
card.addon.disable();
card.addon.enable();
}
""")
if len(fx.window_handles) != 1:
fx.switch_to.window(addonsTabHandle)
fx.close()
i want following script as an executable... it become build and everything... but it doesnt make a token.txt when I run it (also as admin). I dont know if it dont work at all or just the file creation part.
But think its dont work at all... run the exe in cmd dont show the print ...
Also there is opening a geckodriver.exe window.
When I dont drive as admin the exe ask for firewall permission.
When I start the exe every seound time (realy only every secound time)there is comming up an error that say:
"Failed to execute script Etherscrape" (Ethersscrape is the name of the .exe)
Also is there a geckodriver.log what shows an error:
*** You are running in headless mode.
JavaScript error: resource://gre/modules/XULStore.jsm, line 66: Error: Can't find profile directory.
1591714269803 Marionette INFO Listening on port 54219
1591714270054 Marionette WARN TLS certificate errors will be ignored for this session
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from collections import defaultdict
counted = defaultdict(int)
tokenliste = []
options = Options()
options.headless = True
driver = webdriver.Firefox(firefox_options=options)
for x in range(1,10):
my_url = "https://etherscan.io/tokentxns?ps=100&p="+str(x)
driver.get(my_url)
for i in range(1,100):
xpath = "/html/body/div[1]/main/div[2]/div/div/div[2]/table/tbody/tr["+str(i)+"]/td[9]/a"
p_element = driver.find_element_by_xpath(xpath)
tokenliste.append(p_element.text)
for x in tokenliste:
counted[x] += 1
print(counted)
with open("token.txt","w",encoding="utf-8") as f:
for key, value in sorted(counted.items(), key=lambda item: item[1]):
stri = str(key)+ ": " + str(value)+ "\n"
f.write(stri)
I have a Selenium Python test suite. It starts to run but after a few mins the following error is thrown:
Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.ie.service.Service object at 0x0000000002610DD8>> ignored
My test suite implementation is:
import unittest
from HTMLTestRunner2 import HTMLTestRunner
import os
import Regression_TestCase.RegressionProject_TestCase2
# get the directory path to output report file
#result_dir = os.getcwd()
result_dir = r"E:\test_runners\selenium_regression_test_5_1_1\ClearCore - Regression Test\TestReport"
# get all tests from SearchProductTest and HomePageTest class
search_tests = unittest.TestLoader().loadTestsFromTestCase(Regression_TestCase.RegressionProject_TestCase2.RegressionProject_TestCase2)
# create a test suite combining search_test
re_tests = unittest.TestSuite([search_tests])
# open the report file
outfile = open(result_dir + "\TestReport.html", "w")
# configure HTMLTestRunner options
runner = HTMLTestRunner.HTMLTestRunner(stream=outfile,
title='Test Report',
description='Smoke Tests')
# run the suite using HTMLTestRunner
runner.run(re_tests)
Can anyone help why this error is stopping my test suite from running? How do I solve this?
Provided you have installed selenium, and assuming that earlier in the console's traceback log you also got something like "'chromedriver' executable needs to be in PATH" in your script, you should be able to do:
from selenium import webdriver
driver = webdriver.Chrome("/path/to/chromedriver")
This should tell your script where to find chromedriver. On a Mac you can usually use: /usr/local/bin/chromedriver
Download chromium driver from https://sites.google.com/a/chromium.org/chromedriver/downloads
Unzip the file and then from your code, write something like:
from selenium import webdriver
driver = webdriver.Chrome("/path/to/chromedriver")
where /path/to/chromedriver is the location of your chromedriver.
This is the class declaration for Chrome Webdriver: selenium.webdriver.chrome.webdriver.WebDriver(executable_path='chromedriver', ...
taken from https://seleniumhq.github.io/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.webdriver.html#module-selenium.webdriver.chrome.webdriver
Given what #CubeBot88 had already written, another way to get the chromedriver executable in PATH is to do as follow:
from os
from selenium import webdriver
os.environ['PATH'] += "/path/to/chromedriver"
driver = webdriver.Chrome()
The above way puts the path to chromedriver to environment variable PATH only in this program, allowing independent PATH in different situations.
This page comes up first on Google, but only suggests that you are declaring you path incorrectly.
If you are reading this, try making sure the chromedriver is an executable:
run this command in the path of the driver:
sudo chmod a+x chromedriver
I have to download some files from a website, I'm using Python - Selenium - Chrome - Osx.
I have his code so far:
lnk = "www.foobar.com"
CHROMEDRIVER=webdriver.Chrome()
options = webdriver.ChromeOptions()
profile = {"plugins.plugins_list": [{"enabled":False, "name":"Chrome PDF Viewer"}],
"download.default_directory" : TEMP_DOWNLOAD}
options.add_experimental_option("prefs",profile)
driver = webdriver.Chrome(chrome_options = options)
driver.get(lnk)
while True:
if filter(os.path.isfile, glob.glob(TEMP_DOWNLOAD+'/*.crdownload')):
pass
else:
break
driver.quit()
This code starts the download of the file, waits the end of the download and then closes the webdriver.
Everything is working properly except that it opens 2 Chrome windows, one to open the link and the other to download the file, and the quit() method closes only the latter.
Is there a way to kill all the windows opened by Selenium (I'm trying to avoid firing a terminal command to kill the processes brute force)?
EDIT:
as Mukesh Takhtani said in comment in my code the problem is a pointless webdriver instance.
Use this. This I used for Firefox. You can use this for Chrome. Call kill_waste() in your python code and it would kill idle useless Chrome. Please note that this would work for OSX or FreeBSD. For Linux distros you would have to change the way you are going to use grep and cut
import commands
def kill_waste():
(_,firefox_processes) = commands.getstatusoutput("ps -ax | grep '/usr/local/bin/firefox -foreground' | cut -c1-24")
sleep(0.5)
firefox_processes = firefox_processes.splitlines()
for pid in firefox_processes:
values = pid.split()
time_value = values[3].split(':')
if ((values[2] == 'I' or values[2] == 'I+') and time_value[0] == '1') or time_value[0] == '2':
commands.getstatusoutput("kill -9 " + values[0])
I am getting the following errors when running a basic Selenium test script in Python:
======================================================================
ERROR: test_untitled (__main__.TestTesting)
----------------------------------------------------------------------
Traceback (most recent call last):
File "TestTesting.py", line 15, in setUp
self.selenium.start()
File "/usr/lib/python2.6/dist-packages/selenium.py", line 166, in start
result = self.get_string("getNewBrowserSession", [self.browserStartCommand, self.browserURL])
File "/usr/lib/python2.6/dist-packages/selenium.py", line 195, in get_string
result = self.do_command(verb, args)
File "/usr/lib/python2.6/dist-packages/selenium.py", line 191, in do_command
raise Exception, data
Exception: Failed to start new browser session: Error while launching browser
----------------------------------------------------------------------
Ran 1 test in 20.427s
FAILED (errors=1)
The code was generated from the Selenium IDE, the firefox plug in, so I am not sure why it doesn't work. My guess is some sort of configuration is incorrect, but I am not sure. Here is my code:
from selenium import selenium
class TestTesting(unittest.TestCase):
def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 4444, "*firefox", "http://www.google.com/")
self.selenium.start()
def test_untitled(self):
sel = self.selenium
sel.open("/firefox?client=firefox-a&rls=org.mozilla:en-US:official")
sel.type("sf", "test")
sel.click("btnG")
sel.wait_for_page_to_load("30000")
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
The server is running on Ubuntu.
How can I avoid this error?
The fix that I got to work was that the display for firefox was not set. So I needed to execute the following statement:
export DISPLAY=:0
right before I started the Selenium server. This solve the issue, but a new one has arisen.
This normally happens when another firefox is already opened. i.e. You are using specific FF profile to tet application. When you run the script, close FF.
Temporarily launching the selenium server as root did the trick for me:
sudo java -jar selenium-server.jar