I have just started learning Python and I’m diving in at the deep end with Selenium trying to learn from trial and error (so please go easy on me) – I have searched and searched, but I think being new to it all I am just searching for the wrong terms as I’ve had no success
I have moved from PHP, so I will try to explain using that as a crutch
Lets say we have a main script and a login script.
In the main script, we declare a "browser" object for example… The login script then happily uses this browser object to perform login. No issues, it works in PHP
//mainscript.php
require_once("login.php");
$browser = Object.browser;
login();
//login.php
function login(){
//general login stuff goes here
$browser.login();
}
So lets look at Python then… Doing the equivalent in Python
Browser is undefined.
How do I break up scripts in Python into smaller chunks by importing them like in the PHP example? Otherwise it will be one massive file impossible to read and write!?
I need to be able to break the scripts into parts so that functions such as "login" and others do not clog up the main script page, they can be called as required from the main script
//mainscript.py
import login
browser = webdriver.Firefox()
browser.get(webpage)
Login()
//login.py
def Login:
//do some login stuff
browser.find_element(...).click()
I have tried looking on the internet but I think I am searching for the wrong search terms as I am not yet familiar with Python
2
Answers
When you
import login
, you are importing the modulelogin.py
. This imported module contains all of the variables, functions, classes etc. oflogin.py
, but the import statement does not put these into global scope.Due to this, you need to do one of the following:
This is very similar to
require_once
in PHP, but considered poor practise as it can cause namespace pollution and name conflicts.As an aside, function and variable names in python typically begin with a lower case letter by convention, with class names beginning with an upper case letter.
My suggestion is to do some research on the page object model. The basic concept is each page is in a different class file and contains all locators for that page and methods for any actions the user would need to perform on that page. The advantage here is better organization, easier maintenance, code reuse, etc.
Some resources to get you started: