In first file , there is a below code.
I want to use the driver instance of first file in second file , I am able to call it but getting an exception Nosuchelementexception
Basically i want the same browser session in both files , note that import statements are provided properly to use those.
class Init():
driver = webdriver.Chrome(
executable_path="C:\Program Files (x86)\Python36-32\selenium\webdriver\chromedriver_win32\chromedriver.exe")
def take_screenshot(self):
Init.driver.get_screenshot_as_png("Testcase.png")
def browser_launch(self):
Init.driver.set_page_load_timeout(20)
Init.driver.get("http://url/")
Init.driver.maximize_window()
def user_comes_in(self):
Init.driver.find_element_by_id("username").send_keys("admin")
Init.driver.find_element_by_name("password").send_keys("admin")
Init.driver.find_element_by_class_name("Button").click()
Init.driver.set_page_load_timeout(20)
In second file , here is the code
initiate = Init()
class Two(unittest.TestCase):
initiate.browser_launch()
def test_user_logs(self):
initiate.user_comes_in()
print("test case one")
def test_user_create(self):
initiate.user_creation()
print("Test case two")
if you can keep the browser open, you can do it like this:
init.py:
def setDriver():
driver = webdriver.Firefox()
driver.maximize_window()
driver = setDriver()
1.py:
from init.py import driver
driver.get('xxxx')
2.py:
from init.py import driver
driver.get('yyyy')
they will use same driver and same browser.
but if you close the driver in any of the case file, others can't use it again. so it only available in cases don't need to close browser.
Related
I'm new to python and selenium. I want to call a login function from another file and then continue my test within the same driver. I've managed to write a login function > call it from the other file but when I continue with my test, i get the following error, NameError: name 'driver' is not defined
How can I make this work so I can reference the login function to login and then continue writing code without getting the NameError?
Here is the code
file1.py
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
def login(context):
s = Service("C:pythonProject/chromedriver.exe")
# Starts the chrome driver
global driver
driver = webdriver.Chrome(service=s)
driver.maximize_window()
def username(context):
# URL
url = "https://www.bbc.com"
driver.get(url)
driver.implicitly_wait(10)
search = driver.find_element(By.ID, "user")
search.send_keys('xxxxx')
search = driver.find_element(By.ID, "pass")
search.send_keys('xxxxx')
driver.find_element(By.ID, "log_in_button").click()
file2.py
from behave import *
from file1 import *
from selenium.webdriver.common.by import By
#given(u'sdsd')
def step_impl(context):
login(context)
username(context)
#when(u'sdds')
def step_impl(context):
search = driver.find_element(By.ID, "headerBar")
Not even from … import * can give you access to names added by global after the import occurs. (Worse still, if they are reassigned, you’ll still have the old value.)
Just take that as yet another reason not to use that syntax: write
import file1
…:
search = file1.driver.find_element(By.ID, "headerBar")
or better yet have the file1 functions return driver rather than storing it in a global at all.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver=webdriver.chrome(executable_path="C:\Driver\chromedriver_win32\chromedriver.exe")
driver.get("www.youtube.com")
print (driver.title)
driver.close()
for the above code I'm getting the error
TypeError: 'module' object is not callable
I recommend modular programming.
Set a function that returns the chrome driver like such:
# Opens chrome driver
def openChrome():
# directory to chromedrive
chromeDriver = "C:\Driver\chromedriver_win32\chromedriver.exe"
return webdriver.Chrome(chromeDriver)
Call this function like this:
url = "https://stackoverflow.com/"
driver = openChrome()
driver.get(url)
So in the future if your driver isn't working, you don't have to change it on every script you will change it in one place (function)
I am trying to learn python and selenium. and I am using pytest-bdd. and there is conftest.py. Normally I defined my driver in this page under before_scenarios method. And I have basepage which contains click,hover_to,text_presents etc some operations. Conftest also use my BasePage click method to close popups. and I have LoginTest.py which use Basepage.
How can I use driver for all pages. because I cant get driver. What is my mistake also could u pls explain?
Here is my code:
conftest.py:
bp = BasePage.BasePage()
def pytest_bdd_before_scenario():
global driver
url="myurl"
logger.info("\nBrowser operations before test running\n")
driver = webdriver.Chrome()
driver.get(url)
driver.maximize_window()
website_is_up_and_running(url)
bp.click((By.XPATH , "//div[#title='Kapat']"))
bp.click((By.XPATH , "//a[#class='close-button']"))
Here is my BasePage:
class BasePage():
def click(self,driver,by_locator):
WebDriverWait(driver, 60) .until(EC.visibility_of_element_located((by_locator))).click()
And Finally, this is my LoginTest.py:
import utilities.BasePage as BasePage
bp = BasePage.BasePage()
#when('I click the Login Button')
def i_click_the_login_button():
bp.hover_to_and_click(driver,(By.XPATH , "(//p[#class='link-text'])[1]")) //in this line I can't get driver.
I am writing a script that will check if the proxy is working. The program should:
1. Load the proxy from the list (txt).
2. Go to any page (for example wikipedia)
3. If the page has loaded (even not completely) it saves the proxy data to another txt file.
It must all be in the loop. It must also check whether the browser has displayed an error. I have a problem with always turning off the previous browser every time, after several loops several browsers are already open.
Ps. I replaced the iteration with a random number
from selenium import webdriver
import random
from configparser import ConfigParser
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import traceback
while 1:
ini = ConfigParser()
ini.read('liczba_proxy.ini')
random.random()
liczba_losowa = random.randint(1, 999)
f = open('user-agents.txt')
lines = f.readlines()
user_agent = lines[liczba_losowa]
user_agent = str(user_agent)
s = open('proxy_list.txt')
proxy = s.readlines()
i = ini.getint('liczba', 'liczba')
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy[liczba_losowa])
chrome_options.add_argument(f'user-agent={user_agent}')
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='C:\Python\Driver\chromedriver.exe')
driver.get('https://en.wikipedia.org/wiki/Replication_error_phenotype')
def error_catching():
print("error")
driver.stop_client()
traceback.print_stack()
traceback.print_exc()
return False
def presence_of_element(driver, timeout=5):
try:
w = WebDriverWait(driver, timeout)
w.until(EC.presence_of_element_located((By.ID, 'siteNotice')))
print('work')
driver.stop_client()
return True
except:
print('not working')
driver.stop_client()
error_catching()
Without commenting on your code design:
In order to close a driver instance, use driver.close() or driver.quit() instead of your driver.stop_client().
The first one closes the the browser window on which the focus is set.
The second one basically closes all the browser windows and ends the WebDriver session gracefully.
Use
chrome_options.quit()
Obs.: Im pretty sure you should not use testcases like that... "while 1"? so you test will never end?
I guess you should setup your testes in TestCases and call the TheSuite to teste all your testcases and give you one feedback about whant pass or not, and maybe setup one cronjob to keep calling it by time to time.
Here one simple example mine using test cases with django and splinter (splinter is build on top of selenium)
https://github.com/Diegow3b/python-django-basictestcase/blob/master/myApp/tests/test_views.py
I tried to have a separate file for browser driver, in my driver file with a file name driver.py:
from selenium import webdriver
class MyDriver():
def __init__(self):
self.driver = webdriver.Firefox()
I try reusing it on another file here's the code:
from driver import MyDriver
driver = MyDriver()
driver.get('http://google.com')
However, I always got an error:
AttributeError: 'MyDriver' object has no attribute 'get'
You simply forgot to add another driver. Try this:
driver.driver.get('http://google.com')