I'm trying to use the undetected_chromedriver.v2 package in Python Anaconda. My code goes like this:
import undetected_chromedriver.v2 as uc
ucoptions = uc.ChromeOptions()
print('1')
ucoptions.add_argument('--no-first-run')
print('2')
driver = uc.Chrome(chrome_options = ucoptions)
print('3')
In Anaconda Spyder, it works well if I use the F9 key to step into every single line of code and is able to open the Chrome browser normally as expected.
However, whenever I use the F5 key to run the whole file, it always get stuck in the driver = uc.Chrome(chrome_options = ucoptions) line and can only print out "1" and "2" on my screen.
Can anyone help me with this issue? Many thanks!
Hey there just trying a basic browser launch using Firefox.
I've tried using executable path, if statement, and without an if statement and the browser will still not open. I've checked the shell and I don't have an error.My best guess is I'm missing an action of some sort I just need someone to point my in the right direction using my current code, thank you.
from selenium import webdriver
class testbot():
def botfox(self):
driver = self.driver = webdriver.firfox(geckodriver)
driver.get("https://wwww.google.com")
if __name__ == "__botfox__":
botfox()
ok, try this :)
from selenium import webdriver
class testbot():
def botfox(self):
self.driver = webdriver.Firefox()
self.driver.get("https://wwww.google.com")
if __name__ == '__main__':
testBotInstace = testbot()
testBotInstace.botfox()
I'd be surprised if that worked. Have you tried calling it via testbot().botfox() ?
webdriver.firfox would not work, as the syntax is webdriver.Firefox
webdriver.firfox(geckodriver) would not work as geckodriver is not defined anywhere
botfox() would not work because there is no function defined as that. There is one inside of testbot but you would need to first instantiate the class and then call it via testbot().botfox()
My function looks like this:
import selenium.webdriver as webdriver
def test_alpha(browser, sitename):
browser.get(sitename)
if 1:
browser.quit()
return 1
else:
browser.quit()
return 0
def test_beta():
sitename_1 = "https://www.google.com/"
sitename_2 = "https://www.youtube.com/"
chrome = webdriver.Chrome("C:\Python36\selenium\webdriver\chrome\chromedriver.exe")
if test_alpha (chrome, sitename_1):
return 1
else:
return 0
if test_alpha (chrome, sitename_2):
return 1
else:
return 0
When it opens the first webpage (google.com), everything works fine. It closes the browser, and when it goes through the second call of test_alpha (when it has to open youtube.com), I get an error saying that "No connection could be made because the target machine actively refused it".
I've tried turning off windows firewall and my antivirus but it still doesn't work.
Also tried to use browser.quit() along with killing the chrome.exe process. Still doesn't work.
I want to control whether my WebDriver quit but I can't find a method for that. (It seems that in Java there's a way to do it)
from selenium import webdriver
driver = webdriver.Firefox()
driver.quit()
driver # <selenium.webdriver.firefox.webdriver.WebDriver object at 0x108424850>
driver is None # False
I also explored the attributes of WebDriver but I can't locate any specific method to get information on the driver status. Also checking the session id:
driver.session_id # u'7c171019-b24d-5a4d-84ef-9612856af71b'
If you would explore the source code of the python-selenium driver, you would see what the quit() method of the firefox driver is doing:
def quit(self):
"""Quits the driver and close every associated window."""
try:
RemoteWebDriver.quit(self)
except (http_client.BadStatusLine, socket.error):
# Happens if Firefox shutsdown before we've read the response from
# the socket.
pass
self.binary.kill()
try:
shutil.rmtree(self.profile.path)
if self.profile.tempfolder is not None:
shutil.rmtree(self.profile.tempfolder)
except Exception as e:
print(str(e))
There are things you can rely on here: checking for the profile.path to exist or checking the binary.process status. It could work, but you can also see that there are only "external calls" and there is nothing changing on the python-side that would help you indicate that quit() was called.
In other words, you need to make an external call to check the status:
>>> from selenium.webdriver.remote.command import Command
>>> driver.execute(Command.STATUS)
{u'status': 0, u'name': u'getStatus', u'value': {u'os': {u'version': u'unknown', u'arch': u'x86_64', u'name': u'Darwin'}, u'build': {u'time': u'unknown', u'version': u'unknown', u'revision': u'unknown'}}}
>>> driver.quit()
>>> driver.execute(Command.STATUS)
Traceback (most recent call last):
...
socket.error: [Errno 61] Connection refused
You can put it under the try/except and make a reusable function:
import httplib
import socket
from selenium.webdriver.remote.command import Command
def get_status(driver):
try:
driver.execute(Command.STATUS)
return "Alive"
except (socket.error, httplib.CannotSendRequest):
return "Dead"
Usage:
>>> driver = webdriver.Firefox()
>>> get_status(driver)
'Alive'
>>> driver.quit()
>>> get_status(driver)
'Dead'
Another approach would be to make your custom Firefox webdriver and set the session_id to None in quit():
class MyFirefox(webdriver.Firefox):
def quit(self):
webdriver.Firefox.quit(self)
self.session_id = None
Then, you can simply check the session_id value:
>>> driver = MyFirefox()
>>> print driver.session_id
u'69fe0923-0ba1-ee46-8293-2f849c932f43'
>>> driver.quit()
>>> print driver.session_id
None
I ran into the same problem and tried returning the title - this worked for me using chromedriver...
from selenium.common.exceptions import WebDriverException
try:
driver.title
print(True)
except WebDriverException:
print(False)
suggested methods above didn't work for me on selenium version 3.141.0
dir(driver.service) found a few useful options
driver.session_id
driver.service.process
driver.service.assert_process_still_running()
driver.service.assert_process_still_running
I found this SO question when I had a problem with closing an already closed driver, in my case a try catch around the driver.close() worked for my purposes.
try:
driver.close()
print("driver successfully closed.")
except Exception as e:
print("driver already closed.")
also:
import selenium
help(selenium)
to check selenium version number
This work for me:
from selenium import webdriver
driver = webdriver.Chrome()
print( driver.service.is_connectable()) # print True
driver.quit()
print( driver.service.is_connectable()) # print False
How about executing a driver command and checking for an exception:
import httplib, socket
try:
driver.quit()
except httplib.CannotSendRequest:
print "Driver did not terminate"
except socket.error:
print "Driver did not terminate"
else:
print "Driver terminated"
it works in java, checked on FF
((RemoteWebDriver)driver).getSessionId() == null
There is this function:
if driver.service.isconnectible():
print('Good to go')
In my case, I needed to detect whether the browser interface was closed - regardless - chromedriver's status. As such, none of the answers here worked, and I just decided to go for the obvious:
from selenium.common.exceptions import WebDriverException
try:
driver.current_url
print('Selenium is running')
except WebDriverException:
print('Selenium was closed')
Even though it's a bit of a hack, it's served my purposes perfectly.
''''python
def closedriver():
global drivername
drivername.quit()
global driveron
driveron=False
''''
this function "closedriver" uses a global variable named "drivername" and global bool variable named "driveron",you may just pass a current driver as parameter but
NOTE: driveron must be global to store the state of driver being 'on' or 'off'.
''''python
def closedriver(drivername):
global driveron
try:
drivername.quit()
except:
pass
driveron=False
''''
and when you start a new driver, just use a check
global driveron
if not driveron:
driver=webdriver.Chrome()
I am executing selenium test cases via Proboscis, for good reporting of test results. I have the following test case written
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from proboscis import test
import unittest
driver = webdriver.Firefox()
#test(groups=["unit","login"])
class UI_test(unittest.TestCase):
def test_SuccessfulErrorMsgOnEmptyUserName(self):
driver.get("http://127.0.0.1:7999/login/")
username_input = driver.find_element_by_id("id_email")
username_input.send_keys('')
password_input = driver.find_element_by_id("id_password")
password_input.send_keys('bill3')
driver.find_element_by_xpath('//input[#value = "Log In"]').click()
driver.implicitly_wait(3)
driver.find_element_by_class_name("error-login")
driver.close()
def run_tests():
from proboscis import TestProgram
# from tests import unit
# Run Proboscis and exit.
TestProgram().run_and_exit()
if __name__ == '__main__':
run_tests()
What could be causing the BadStatusLine exception in this code?
Looks like a duplicate of Python/Django "BadStatusLine" error but i can't flag due to this question having a bounty. According to this answer, a BadStatusLine exception is likely caused by an empty response, as in there being no status line at all.
According to this answer, the server formally tells the client there is no more data, instead of simply causing a connection reset or rude timeout.