DeprecationWarning with selenium/geckodriver - python

What does the DeprecationWarning mean?
Also it seems like if i delete the "elem" functions it kind of works but when the chrome tab opens with the link it immediatelly closes again
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyautogui
import unittest
import time
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(
executable_path=r'C:\Users\iwanh\Desktop\Geckodriver\geckodriver.exe')
def test_search_in_python_org_true(self):
driver = self.driver
driver.get("https://e-learning.nyc.gr/login/index.php")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
time.sleep(3)
elem.send_keys(Keys.RETURN)
self.assertNotIn("No results found.", driver.page_source)
def test_search_in_python_org_false(self):
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("ljueragiuhoerg")
elem.send_keys(Keys.RETURN)
time.sleep(2)
self.assertIn("No results found.", driver.page_source)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
Outputs of code
Output 1
Output 2

With selenium4 as the key executable_path is deprecated you have to use an instance of the Service() class along with ChromeDriverManager().install() command as below.
Pre-requisites
Ensure that: Selenium is upgraded to v4.0.0
Solutions:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.google.com")

Related

Facing this error in Pytest on selenium python

import time
import self as self
from pytest import mark
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from setuptools import setup
#mark.execute
class First_Tests:
def test_first(self, setup):
driver = setup['driver']
browser = setup['browser']
driver.get("https://shuftipro.com/")
driver.maximize_window()
def header_test(self, setup):
driver = setup['driver']
# Click on solution in header
solution = driver.find_element(By.ID, "menu-item-72751")
solution.click()
if driver.current_url == "https://shuftipro.com/solutions/":
print("land on solution page.")
else:
print("land on wrong page.")
obj = First_Tests()
obj.test_first(self, setup)
obj.header_test(self, setup)
If I remove the "self" from parameter and run the program it showing me error that, test_first() takes 1 positional arguments but 3 were given
one of easier way would be to use webdriver from selenium
driver = webdriver.Chrome()
and remove
driver = setup['driver']
browser = setup['browser']
and then get rid of setup as parameter.
The final code will look something like this:
from pytest import mark
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
#mark.execute
class First_Tests:
def test_first(self):
driver.get("https://shuftipro.com/")
driver.maximize_window()
def header_test(self):
# Click on solution in header
solution = driver.find_element(By.ID, "menu-item-72751")
solution.click()
if driver.current_url == "https://shuftipro.com/solutions/":
print("land on solution page.")
else:
print("land on wrong page.")
obj = First_Tests()
obj.test_first()
obj.header_test()

I tried to assert a driver.find_element but the result says AttributeError: type object 'By' has no attribute 'id'

I tried to access a website and find its element. The result says:
AttributeError: type object 'By' has no attribute 'id'.
import unittest from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
class test_case(unittest.TestCase):
def testName(self):
driver = webdriver.Chrome(options=chrome_options)
driver.get("bing.com/?rtc=1")
Element = driver.find_element(By.ID, "container")
self.assertIsNone(Element, "ID element is not none") # (to be continued)
if name == 'main':
unittest.main()
I want to use the assertIsNone() but in console, the result says it ran but has Errors=1.
I want to display a message using the syntax assertIsNone but it did not occur on the console. What should I do about the error?
Is that what you need?:
import unittest from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
class test_case(unittest.TestCase):
def testName(self):
driver = webdriver.Chrome(options=chrome_options)
driver.get("bing.com/?rtc=1")
try:
Element = driver.find_element(By.ID, "container")
success = True
except:
success = False
self.assert(success, True) # (to be continued)
if name == 'main':
unittest.main()
If not, feel free to tell me the issue, and I'll edit my answer.

Docker selenium not redirecting on another page in django test

I have some issue with docker selenium. For example, I have tried it on local selenium using operadriver, so redirecting to another page, after submit form, was working.I want to see this result also in django selenium test, but I've just get selenium.common.exceptions.TimeoutException: Message: in waiting when url will change.
This is my test code
import os
import socket
import shutil
# from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from django.test import LiveServerTestCase
from django.conf import settings
# Create your tests here.
class LandFormTest(LiveServerTestCase):
host = socket.gethostbyname(socket.gethostname())
def setUp(cls):
selenium_url = 'http://selenium:4444/wd/hub'
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--headless')
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--ignore-certificate-errors")
# options.add_argument("My user agent")
options.add_argument(f"window-size=1920,1080")
cls.driver = webdriver.Remote(
command_executor=selenium_url,
desired_capabilities=DesiredCapabilities.CHROME,
options=options
)
def test_form(self):
try:
driver = self.driver
domain = self.live_server_url.split('//')[1].split(':')[0]
if not settings.BASE_DIR.joinpath(f'templates/lands/{domain}').is_dir():
src = f'templates/lands/quantum.localhost'
dest = f'templates/lands/{domain}'
shutil.copytree(src, dest)
driver.get(f'{self.live_server_url}/api/v1/test/?ai=2&gi=5')
user_firstname = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.NAME, "firstname"))
)
current_url = driver.current_url
user_firstname = driver.find_element(By.NAME, 'firstname')
user_lastname = driver.find_element(By.NAME, 'lastname')
user_email = driver.find_element(By.NAME, 'email')
user_phone = driver.find_element(By.NAME, 'phone')
user_firstname.send_keys('test')
user_lastname.send_keys('test')
user_email.send_keys('test#gmail.com')
user_phone.send_keys('+(846)411-36-00')
user_phone.submit()
WebDriverWait(driver, 10).until(EC.url_changes(current_url))
print(driver.current_url)
print(driver.page_source)
assert 'Hello World' in driver.page_source
except Exception as e:
raise(e)
def tearDown(self):
self.driver.quit()
My /api/v1/test/ url get static and template in folder by domain name, so I copy the default folder "quantum.localhost" and rename it to ip of docker. The main problem is that is working locally with driver, but not with docker and django. Want to notice that I am also tried to use firefox selenium. Thanks for help!

Selenium WebDriver : AttributeError: 'WebDriver' object has no attribute 'ChromeOptions'

I made a successfull unit test with Selenium WebDriver python. This latter downloads a file in a custom location that I've defined, assert the file had been correctly downloded and delete it.
Here is its code :
import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions() ;
prefs = {"download.default_directory" : "C:\\Users\\AminataWillane\\Desktop\\selenium_download"}
options.add_experimental_option("prefs",prefs);
driver = webdriver.Chrome(executable_path='./chromedriver',chrome_options=options)
driver.get('https://www.browserstack.com/test-on-the-right-mobile-devices');
gotit= driver.find_element(By.ID,'accept-cookie-notification');
gotit.click();
downloadcsv= driver.find_element(By.CSS_SELECTOR, '.icon-csv')
downloadcsv.click();
time.sleep(10)
#check file
try:
print('try started')
if os.path.isfile('C:\\Users\\AminataWillane\\Desktop\\selenium_download\\BrowserStack - List of devices to test on.csv'):
print("File download is completed and the file will be deleted")
time.sleep(5)
os.remove("C:\\Users\\AminataWillane\\Desktop\\selenium_download\\BrowserStack - List of devices to test on.csv")
print("File had been removed successfully")
except FileNotFoundError as er:
print("File Not Found !")
Then once I tried out the same logic while implementing Page Object Model, it isn't working :
here is the related code :
import os
import time
from seleniumpagefactory.Pagefactory import PageFactory
from selenium.webdriver.support.select import Select
from selenium.webdriver.chrome.options import Options
from test.test_download import options
class QA_download_me(PageFactory):
def __init__(self, driver):
self.driver = driver
options = driver.ChromeOptions();
prefs = {"download.default_directory": "C:\\Users\\AminataWillane\\Desktop\\selenium_download"}
options.add_experimental_option("prefs", prefs);
driver.Chrome(executable_path='./chromedriver', chrome_options=options)
locators = {
"documentation": ('ID', 'NavLinkDocumentation'),
"sdk": ('ID', 'NavLinkDocumentation1'),
"download_btn": ('XPATH', '//*[#id="server-root"]/div/div/main/div/div/div[2]/div/div[2]/div/div/a[1]'),
}
def download_me(self):
# create a service
self.documentation.click_button()
time.sleep(5)
self.sdk.click_button()
time.sleep(5)
self.download_btn.click_button()
time.sleep(10)
try:
print('try started')
if os.path.isfile(
'C:\\Users\\AminataWillane\\Desktop\\selenium_download\\MyriadSDK-latest.tgz'):
print("File download is completed and the file will be deleted")
time.sleep(5)
os.remove(
"C:\\Users\\AminataWillane\\Desktop\\selenium_download\\MyriadSDK-latest.tgz")
print("File had been removed successfully")
except FileNotFoundError as er:
print("File Not Found !")
Here is the error I've got :
ERROR: test_download_me (test.test_book_2.TestLoginTwo)
down= QA_download_me(self.driver)
File "C:\Users\AminataWillane\PycharmProjects\myProj\src\pages\download_me.py", line 15, in __init__
options = driver.ChromeOptions();
AttributeError: 'WebDriver' object has no attribute 'ChromeOptions'
in the second code snipper, when ur calling ChromeOptions() from driver, driver is only self.driver and hasn't yet been identified as selenium.webdriver.
try adding to imports:
from selenium import webdriver
and then say:
options = webdriver.ChromeOptions()
this also goes for when you instantiate your webdriver later (remove self.driver = driver from beginning of code):
self.driver = webdriver.Chrome(...)

Pytest, selenium, fixture throws an error after the first test InvalidSessionIdException

I have a fixture file.
import pytest
from selenium.webdriver.chrome.options import Options as chrome_options
from driver.singleton_driver import WebDriver
#pytest.fixture
def get_chrome_options():
options = chrome_options()
options.add_argument('chrome')
options.add_argument('--start-maximized')
options.add_argument('--window-size=1920,1080')
options.add_argument('--incognito')
return options
#pytest.fixture
def get_webdriver(get_chrome_options):
options = get_chrome_options
driver = WebDriver(options).driver
return driver
#pytest.fixture(scope='function')
def setup(request, get_webdriver):
driver = get_webdriver
if request.cls is not None:
request.cls.driver = driver
yield driver
driver.close()
File with my tests
import pytest
#pytest.mark.usefixtures('setup')
class TestSteamPages:
def test_first(self):
self.driver.get('https://www.google.com/')
def test_second(self):
self.driver.get('https://www.google.com/')
As I understand it, after the first test, the function in the driver.close() fixture is triggered. But when the second test is run, the fixture does not restart the webdriver. An error
venv/lib/python3.10/site-packages/selenium/webdriver/remote/errorhandler.py:243: InvalidSessionIdException
============================================================================== short test summary info ==============================================================================
FAILED tests/test_first.py::TestSteamPages::test_second -
selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id
ERROR tests/test_first.py::TestSteamPages::test_second - selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id
For the driver, I use the Singleton pattern
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
class WebDriver:
class __WebDriver:
def __init__(self, options):
self.driver = webdriver.Chrome(options=options, service=ChromeService(ChromeDriverManager().install()))
driver = None
def __init__(self, options):
if not self.driver:
WebDriver.driver = WebDriver.__WebDriver(options=options).driver
The driver is not reinitialized because of the singleton. WebDriver.driver is initialized before first test, so in the next time setup is running if not self.driver is False, because self.driver is not None anymore.
If you want to initialize the WebDriver every test don't use singleton
#pytest.fixture
def get_webdriver(get_chrome_options):
options = get_chrome_options
driver = webdriver.Chrome(options=options, service=ChromeService(ChromeDriverManager().install()))
return driver
If you do want to initialize the WebDriver only once you can change fixtures scope to 'class' (for all tests in TestSteamPages) or even move it to conftest.py with scope 'session' for one driver instance for all the test. Note that in this case all the fixtures need to have scope='class'
#pytest.fixture(scope='class')
def setup(request, get_webdriver):
driver = get_webdriver
if request.cls is not None:
request.cls.driver = driver
yield driver
driver.close()

Categories