Good Day Ahead.
After searching numerious posts in Stackoverflow, I tried to write and implement the automation using selenium and python programming.
I tried my first code as below and i am getting error.
My browser opens and closes very fast. It throws error in the output.
Code:-
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
s=Service(ChromeDriverManager().install())
chrome_driver = webdriver.Chrome(service=s)
browser = webdriver.Chrome("/home/halovivek/Documents/Automation/selenium_driver/")
browser.implicitly_wait(5)
browser.get("https://www.google.com")
#browser.get("https://kite.zerodha.com/")
browser.implicitly_wait(5)
Error:-
/home/halovivek/PycharmProjects/yearcoding/venv/bin/python /home/halovivek/PycharmProjects/yearcoding/06092022_selenium1.py
/home/halovivek/PycharmProjects/yearcoding/06092022_selenium1.py:9: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
browser = webdriver.Chrome("/home/halovivek/Documents/Automation/selenium_driver/")
Traceback (most recent call last):
File "/home/halovivek/PycharmProjects/yearcoding/venv/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 71, in start
self.process = subprocess.Popen(cmd, env=self.env,
File "/usr/lib/python3.10/subprocess.py", line 966, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.10/subprocess.py", line 1842, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
PermissionError: [Errno 13] Permission denied: '/home/halovivek/Documents/Automation/selenium_driver/'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/halovivek/PycharmProjects/yearcoding/06092022_selenium1.py", line 9, in <module>
browser = webdriver.Chrome("/home/halovivek/Documents/Automation/selenium_driver/")
File "/home/halovivek/PycharmProjects/yearcoding/venv/lib/python3.10/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "/home/halovivek/PycharmProjects/yearcoding/venv/lib/python3.10/site-packages/selenium/webdriver/chromium/webdriver.py", line 89, in __init__
self.service.start()
File "/home/halovivek/PycharmProjects/yearcoding/venv/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 86, in start
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: '' executable may have wrong permissions. Please see https://chromedriver.chromium.org/home
Process finished with exit code 1
Please help me
I don't understand why this line comes
browser = webdriver.Chrome("/home/halovivek/Documents/Automation/selenium_driver/")
After you already properly created webdriver instance with
s=Service(ChromeDriverManager().install())
chrome_driver = webdriver.Chrome(service=s)
?
Looks like your code should be as following:
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
s=Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
driver.implicitly_wait(5)
driver.get("https://www.google.com")
UPD
To make your browser stay opened add "detach", True option, as following:
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
s=Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s, chrome_options=chrome_options)
driver.implicitly_wait(5)
driver.get("https://www.google.com")
Related
I am using EdgeDriver with Selenium and Python 3
I have been able to fix it by manually creating the js folder, but the EdgeDriver window does not load the page, it is showing Data;, in the address bar. These may be related on unrelated errors.
But the scoped_dir13788_764300980 changes when restarting the cmd prompt.
The abridged code is below:
# importing required package of webdriver
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from time import sleep
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.opera.options import Options
from selenium.webdriver.support.wait import WebDriverWait
import schedule
import time
from random import randint
def job():
while True:
# Instantiate the webdriver with the executable location of MS Edge
browser = webdriver.Edge(r"C:\Users\*****\Desktop\msedgedriver.exe")
sleep(2)
browser.maximize_window()
sleep(2)
browser.get('https://********/) #masked the name of website on purpose
try:
# Get the text box to insert Email using selector ID
myElem_1 = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'anti-myhub')))
sleep(3)
# Entering the email address
myElem_1.click()
The full error is (ip and user names masked):
[20444:17192:0308/100926.524:ERROR:storage_reserve.cc(164)] Failed to open file to mark as storage reserve: C:\Users\*****\AppData\Local\Temp\scoped_dir13788_764300980\Default\Code Cache\js
DevTools listening on ws://127.0.0.1:59454/devtools/browser/416f15a9-5a69-4025-9322-003aa9672acc
Traceback (most recent call last):
File "check.py", line 79, in <module>
job()
File "check.py", line 21, in job
browser = webdriver.Edge(r"C:\Users\******\Desktop\msedgedriver.exe")
File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\edge\webdriver.py", line 66, in __init__
desired_capabilities=capabilities)
File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created
from tab crashed
(Session info: MicrosoftEdge=**.**.**.**)
I tried to put in the msedge exe in the rool folder and gave the path as "executable_path = '.\msedgedriver.exe'".
when i run my script , i got this error
Traceback (most recent call last):
File "C:\Users\ishaq\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
File "C:\Users\ishaq\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 707, in __init__
restore_signals, start_new_session)
File "C:\Users\ishaq\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 992, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/ishaq/AppData/Local/Programs/Python/Python36/headless.py", line 9, in <module>
driver = webdriver.Chrome(executable_path=os.path.abspath("chromedriver"), chrome_options=chrome_options)
File "C:\Users\ishaq\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__
self.service.start()
File "C:\Users\ishaq\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
here is my script
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.binary_location =
r'C:\Users\ishaq\Desktop\chrome\chromedriver.exe'
driver = webdriver.Chrome(executable_path=os.path.abspath("chromedriver"),
chrome_options=chrome_options)
driver.get("http://www.duo.com")
magnifying_glass = driver.find_element_by_id("js-open-icon")
if magnifying_glass.is_displayed():
magnifying_glass.click()
else:
menu_button = driver.find_element_by_css_selector(".menu-trigger.local")
menu_button.click()
search_field = driver.find_element_by_id("site-search")
search_field.clear()
search_field.send_keys("Olabode")
search_field.send_keys(Keys.RETURN)
assert "Looking Back at Android Security in 2016" in driver.page_source
driver.close()
If we analyze the logs it seems the main issue is with in start os.path.basename(self.path) and subsequent error message:
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH
So it's clear from the error that the Python client was unable to locate the chromedriver executable binary.
You need to take care of a couple of things as follows:
chrome_options.binary_location : The parameter points to the chrome.exe not the chromedriver.exe
os.path.abspath("chromedriver") will pick up the file path of chromedriver but won't append chromedriver.exe at the end.
Here is the sample code on my windows-8 system to start google-chrome-headless:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://www.duo.com")
print("Chrome Browser Initialized in Headless Mode")
driver.quit()
print("Driver Exited")
This question already has answers here:
How can I reconnect to the browser opened by webdriver with selenium?
(4 answers)
Closed 2 years ago.
I was following this tutorial (link below), but an error is happening that I don't know how I can solve it.
https://medium.com/#harith.sankalpa/connect-selenium-driver-to-an-existing-chrome-browser-instance-41435b67affd
I am trying to use the browser that is open to perform a search, because it is already logged into the account that I need.
I'm using chrome --remote-debugging-port=1024 to open chrome, after I execute this code below.
I found some solutions, but none solved my problem, either because the solution was in Java and I didn't understand or I didn't know how to rewrite in python.
Code:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
if __name__ == '__main__':
options = ChromeOptions()
options.add_argument('start-maximized')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--remote-debugging-port=1024')
options.add_argument('--disable-setuid-sandbox')
options.add_experimental_option("debuggerAddress", "localhost:1024")
options.binary_location = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
d = DesiredCapabilities.CHROME
d["loggingPrefs"] = {"browser": "ALL"}
driver = webdriver.Chrome(
executable_path=ChromeDriverManager().install(),
options=options,
desired_capabilities=d
)
driver.get("https://google.com.br")
Error:
Traceback (most recent call last):
File "C:/Users/danit/Desktop/project/main.py", line 22, in <module>
desired_capabilities=d
File "C:\Users\danit\Desktop\project\venv\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 81, in __init__
desired_capabilities=desired_capabilities)
File "C:\Users\danit\Desktop\project\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "C:\Users\danit\Desktop\project\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Users\danit\Desktop\project\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\danit\Desktop\project\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at localhost:1024
from chrome not reachable
Thanks a lot.
The error says chrome is not reachable. Most probably that instance has been deleted
I am showing a simple method to save session data( all cookies will be saved ) and then load selenium to load from that instance.
Look at the following example
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
session = "mySession"
chrome_driver_path = '/home/aahnik/Downloads/apps/chromedriver'
whatsapp_web_url = "https://web.whatsapp.com/"
chrome_options = Options()
chrome_options.add_argument(f'--user-data-dir={session}')
driver = webdriver.Chrome(
options=chrome_options, executable_path=chrome_driver_path)
driver.get(whatsapp_web_url)
Now execute this code. WhatsApp web will open. Login by scanning the QR Code.
Now close the window, and then terminate the program.
Now will see a folder named mySession in your current user directory.
Execute this code again.
This time you will find that you are already logged into WhatsApp.
Hope this helped.
I am very new to python and trying to build a solution using Python + Selenium.
I have created a module to initialize my webdriver:
DriverEngine.py:
import os
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from MyFirstSeleniumPyProject.FrameworkEngine.Constants import BrowserConstants
class DriverInitialize:
def InitializeChromeDriver(self):
browser_name = BrowserConstants.Chrome
print(browser_name)
driver = DriverConfiguration.ConfigureChromeDriver(None)
return driver
class DriverConfiguration:
def ConfigureChromeDriver(self):
driver = webdriver.Chrome(ChromeDriverManager().install())
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("window-size=1920,1080")
# preferences
chrome_options.add_experimental_option('prefs', {
'download.default_directory': get_download_path(),
'profile': {
'password_manager_enabled': False,
'disable-popup-blocking': 'true'
}
})
driver = webdriver.Chrome(chrome_options=chrome_options)
return driver
def get_download_path():
dir_path = os.getcwd()
return dir_path
I'm trying to invoke above driver function in my test file:
Chrome_Test.py
from MyFirstSeleniumPyProject.FrameworkEngine.Drivers import DriverEngine
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
class AssertGooglePage:
def navigate_url(self,url):
self.driver = DriverEngine.DriverInitialize.InitializeChromeDriver(None)
self.driver.get(url)
AssertGooglePage.navigate_url(None, url="https://www.google.com")
ErrorLog:
C:\Users\user\PycharmProjects\TestAutomation.Selenium.Practice\venv\Scripts\python.exe C:/Users/user/PycharmProjects/TestAutomation.Selenium.Practice/MyFirstSeleniumPyProject/Tests/Chrome_Test.py
Chrome
[WDM] - Current google-chrome version is 84.0.4147
[WDM] - Get LATEST driver version for 84.0.4147
[WDM] - Driver [C:\Users\user\.wdm\drivers\chromedriver\win32\84.0.4147.30\chromedriver.exe] found in cache
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\TestAutomation.Selenium.Practice\venv\lib\site-packages\selenium\webdriver\common\service.py", line 72, in start
self.process = subprocess.Popen(cmd, env=self.env,
File "C:\Users\sande\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\sande\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/TestAutomation.Selenium.Practice/MyFirstSeleniumPyProject/Tests/Chrome_Test.py", line 10, in <module>
my = AssertGooglePage.navigate_url(None, url="https://www.google.com")
File "C:/Users/user/PycharmProjects/TestAutomation.Selenium.Practice/MyFirstSeleniumPyProject/Tests/Chrome_Test.py", line 7, in navigate_url
self.driver = DriverEngine.DriverInitialize.InitializeChromeDriver(None)
File "C:\Users\user\PycharmProjects\TestAutomation.Selenium.Practice\MyFirstSeleniumPyProject\FrameworkEngine\Drivers\DriverEngine.py", line 11, in InitializeChromeDriver
driver = DriverConfiguration.ConfigureChromeDriver(None)
File "C:\Users\user\PycharmProjects\TestAutomation.Selenium.Practice\MyFirstSeleniumPyProject\FrameworkEngine\Drivers\DriverEngine.py", line 47, in ConfigureChromeDriver
driver = webdriver.Chrome(chrome_options=chrome_options)
File "C:\Users\user\PycharmProjects\TestAutomation.Selenium.Practice\venv\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
self.service.start()
File "C:\Users\user\PycharmProjects\TestAutomation.Selenium.Practice\venv\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
When I use similar snippet in same file, it works perfectly:
from selenium import webdriver
#import chromedriver_binary
from webdriver_manager.chrome import ChromeDriverManager
import time
# Select webdriver
driver = webdriver.Chrome(ChromeDriverManager().install())
# Select page load time out
driver.set_page_load_timeout(10)
# Navigate to url
driver.get("https://www.google.com")
# Sleep
time.sleep(3)
# Assertion
isTitle = driver.title=="Google"
if(isTitle):
print("Google page opened successfully!")
else:
print("Google page did not opened successfully!")
driver.quit()
Can some one suggest what's wrong with my scripts?
Please Note: I am not keeping Chromedriver at any location instead downloading at run time.
Seems like your script does not know where you Chrome Driver (Selenium) is located.
Try to use the following code to point Selenium to where you downloaded the Chrome Driver:
driver = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
I tried to open a site in firefox through selenium python, when i run the code it opens firefox after that nothing happens ,
WATCH THIS --> HOW TO USE FIREFOX IN PYTHON & HOW TO SET VALUES IN DROP-DOWN LISTS?
here is the error
bash-3.1$ C:/Users/user/AppData/Local/Programs/Python/Python35-32/python.exe d:/PYTHONS/EXTRACT-NEWS/FFD
RIVER.py
Traceback (most recent call last):
File "d:/PYTHONS/EXTRACT-NEWS/FFDRIVER.py", line 23, in <module>
executable_path=r"D:\\PYTHONS\\DRIVERS\\geckodriver.exe")
File "c:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 174, in __init__
keep_alive=True)
File "c:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "c:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "c:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "c:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: newSession
WHEN I RUN THE CODE I GOT THIS ERR
HOW TO USE FF IN PYTHON?
THX IN ADVANCE
# Import Libraries
import os
import sys
import time
from selenium import webdriver
import selenium.webdriver.firefox.options
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# Configure Firefox Options
profile = webdriver.Firefox(
executable_path=r"D:\\PYTHONS\\DRIVERS\\geckodriver.exe")
# 0 means to download to the desktop, 1 means to download to the default "Downloads" directory, 2 means to use the directory
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.dir", download_path)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference(
"browser.helperApps.neverAsk.saveToDisk", "application/x-gzip/text/csv")
os.system("cls")
# firefox_profile=profile
driver = webdriver.Firefox(firefox_profile=profile)
driver.get('https://www.google.com')
print(driver.title)
# driver.quit()
[1]: https://i.stack.imgur.com/T3Bf8.png
To set preference you have to use FirefoxProfile() instead of Firefox()
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.dir", '.')
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip/text/csv")
driver = webdriver.Firefox(firefox_profile=profile, executable_path="D:\\PYTHONS\\DRIVERS\\geckodriver.exe")
driver.get('https://www.google.com')
print(driver.title)
BTW: and don't run webdriver.Firefox() two times beacuse Selenium doesn't know how to run two browsers at the same time - and this gave you error message.