I am looking to use selenium to separate functions based on css selectors - how can this be achieved

I am attempting to modularize my script by breaking it down into various functions for easier reuse. However, when I do so, selenium seems to have trouble locating CSS selectors.

Here is my folder structure:

  • Startup.py
  • Webdriver folder
    • Contains init.py
    • and login.py

startup.py

from selenium import webdriver
from webtesting import login

def browser(usernamefield, passwordfield, loginbutton):
    print 'Starting Firefox'
    browser = webdriver.Firefox()
    print 'Navigating to website address'
    browser.get('website address')
    login.loginsteps(usernamefield, passwordfield, loginbutton)

usernamefield = '#login-username'
passwordfield = 'input.input-default:nth-child(5)'
loginbutton = '.button'

if __name__=='__main__':
    browser(usernamefield,passwordfield,loginbutton)

login.py

def loginsteps(usernamefield, passwordfield, loginbutton):
    try:
        userlogin = browser.find_element_by_css_selector(usernamefield)
        print 'Found <%s> element with that class name!' % (userlogin)
    except:
        print 'Unable to find an element <%s> with that name.' % (usernamefield)
    try:
        userpass = browser.find_element_by_css_selector(passwordfield)
        print 'Found <%s> element with that class name!' % (userpass)
    except:
        print 'Unable to find an element <%s> with that name.' % (passwordfield)
    try:
        logincss = browser.find_element_by_css_selector(loginbutton)
        print 'Found <%s> element with that class name!' % (logincss)
    except:
        print 'Unable to click login.'
    except:
        print 'Unable to find login element.'

Although the browser starts up when I run the script, I encounter exceptions regarding the CSS selectors. This causes the second function to not execute correctly in the browser session.

Output in the terminal:

  • Starting Firefox
  • Navigating to website address
  • Unable to find an element <#login-username> with that name.
  • Unable to find an element with that name.
  • Unable to find login element.

However, it works when I test it all within one function.

from selenium import webdriver

def browser(usernamefield, passwordfield, loginbutton):
    print 'Starting Firefox'
    browser = webdriver.Firefox()
    print 'Navigating to website'
    browser.get('website')
    #login.loginsteps(usernamefield, passwordfield, loginbutton)
    try:
        userlogin = browser.find_element_by_css_selector(usernamefield)
        print 'Found usernamefield element with that class name!'
    except:
        print 'Unable to find an element <%s> with that name.' % (usernamefield)
    try:
        userpass = browser.find_element_by_css_selector(passwordfield)
        print 'Found userpass element with that class name!'
    except:
        print 'Unable to find an element <%s> with that name.' % (passwordfield)
    try:
        logincss = browser.find_element_by_css_selector(loginbutton)
        print 'Found loginbutton element with that class name!'
    except:
        print 'Unable to find login element.'

usernamefield = '#login-username'
passwordfield = 'input.input-default:nth-child(5)'
loginbutton = '.button'

if __name__=='__main__':
    startup.browser(usernamefield, passwordfield, loginbutton)

This method works, but it results in a messy script that cannot be easily broken down into separate functions for code reuse.

  • Starting Firefox
  • Navigating to website
  • Found usernamefield element with that class name!
  • Found userpass element with that class name!
  • Found loginbutton element with that class name!

How can I make Python Selenium work with separate functions? Currently, I am forced to duplicate my script instead of being able to reuse code fragments.

Answer №1

Resolved the issue: The browser variable needs to be returned and passed into the next function

    from selenium import webdriver
    from webtesting import login

    def browser(usernamefield, passwordfield, loginbutton):
        print 'Starting up Firefox'
        browser = webdriver.Firefox()
        print 'Browsing to website address'
        browser.get('website address')
        return browser

if __name__ == '__main__':
    browser = browser()
    loginsteps(browser, usernamefield, passwordfield, loginbutton)

Then pass the browser to the next script so it can pick up the correct browser session.

def loginsteps(browser, usernamefield, passwordfield, loginbutton):
    try:
        userlogin = browser.find_element_by_css_selector(usernamefield)
        print 'Found <%s> element with that class name!' % (userlogin)
    except:
        print 'Was not able to find an element <%s> with that name.' % (usernamefield)
    try:
        userpass = browser.find_element_by_css_selector(passwordfield)
        print 'Found <%s> element with that class name!' % (userpass)
    except:
        print 'Was not able to find an element <%s> with that name.' % (passwordfield)
    try:
        logincss = browser.find_element_by_css_selector(loginbutton)
        print 'Found <%s> element with that class name!' % (logincss)
        except:
            print 'Was not able to click login.'
    except:
        print 'Was not able to find login element.'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tabbable bootstrap with dropdown functionality

I am currently in the process of integrating Bootstrap tabs and dropdown menus using version 2.3.4 <div class="container"> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> ...

Exploring the fundamentals of Django with a touch of creativity in CSS

As a newcomer to Django, I am currently working on setting up a basic Django application. I have progressed to chapter 5 in the Django online book: Before delving into databases, my goal is to incorporate some simple CSS and JS directly into the applicat ...

Ways to modify the cursor of a disabled ImageButton on an ASP.Net webpage

Within a ListView, I have dynamically generated ImageButtons. If an image does not have a link, I want to make it disabled. In the ItemDataBound event, I attempted the following approach: img.Enabled = False img.DescriptionUrl = "javascript:void(0);" img. ...

Mysterious gap found between image and table

Hey there! I've been struggling with an unusual gap between a top image and a table on my website (www.tradecaptaincoaching.com). The table was created using . Despite spending hours on it, I can't seem to get rid of the huge 200 pixel gap that& ...

Uncover the content of an element with Selenium in Java

I need to extract the message "We didn't recognize that email and/or password." using Selenium with Java. <div class="styles_errorDisplayInnerContainer_3R2ni-zSvPIKWfKXiviJhH"> <span class="styles_questionMarkContainer_10mxHNOMojCyG6bxLH ...

Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality. However, I am facing an issue where I want the two SVGs to align v ...

Tips for handling select_input in Rails Cucumber step definitions:

I'm currently integrating cucumber with selenium chrome driver into my project. Currently, I am developing the scenario for creating a new post using CRUD operations. Within the step definition, I need to populate the form with both input and select ...

Unable to create Extent Reports while executing classes simultaneously using TestNG

While running classes in parallel with TestNG, the Extent Report is not generated, but the TestNG report is being updated. Below is a sample code and the versions I am currently using: If we run only one class (TestClass1.java), then the Extent Report will ...

Tips for Troubleshooting Selenium Using Python

I'm encountering a problem where Selenium is not performing as intended. In my Python script, I locate an element by its id. If the node is visible, I proceed to click on it and capture a screenshot. However, the current behavior is unexpected. Selen ...

Div content with a unique angle

I need to create a website with slanted div elements that must meet the following criteria: The sections should have a height of approximately 400px when displayed side by side, and about 800px when they stack vertically. It would be ideal if this could ...

Well, it appears that I am having trouble establishing a connection between the users in this chatting application

I'm encountering a problem with establishing a connection between two users. I have already installed express and socket.io, but for some reason, the message is not getting through to the receiver's end. The code seems to be running fine as I can ...

Slow loading times on websites while using Selenium with VBA

Recently, I have been utilizing Selenium VBA for some of my automation tasks. However, I have noticed that the webpages are taking significantly longer to load compared to when using the Chrome browser directly. Specifically, after successfully logging in ...

The color of the progress bar in JS is not displaying properly

My work involves using jQuery to manipulate progress bars. The issue I am facing is defining standard colors that should be displayed on the progress bar based on the value received. Here is my code: var defaultSegmentColors = ['#FF6363', &ap ...

Ways to showcase solely the visible images using Selenium automation scripts

Currently my application is showing 12 images on the front end, but when accessed through xpath, it shows 18 images. The xpath used is: driver.findElemnt(By.xpath("xpath")).size(); The code used is: int showCount = driver.findElements(By.xpath(ObjRepoP ...

Is there a way to use JavaScript or jQuery to automatically convert HTML/CSS files into PDF documents?

While using OS X, I noticed that in Chrome I have the option to Save as PDF in the print window by setting the destination to "Save as PDF". Is this feature available on Windows? Is there a way to easily save to PDF with just one click? How can I access t ...

Creating Transparent Rounded Backgrounds in Google Chrome Packaged Apps: Achieving the same look as Google Hangout app

Looking at the screenshot below, it is evident that the Hangout app has a fully transparent design with background shadow effect applied to it. I have tried various methods in vain, such as applying CSS styling to the "html" and "body" tags of the page, a ...

What is the best way to use jQuery to animate a particular height up to 100%?

To provide a sneak peek of the content in the div, I have minimized it so only the first line is visible. Now, I want to add an animation that will expand the div to 100% height when you click the title. However, using animate(height:"100%") does not res ...

Running Protractor tests with headless Chrome on MacOS using XVFB

For my Angular Application, I am looking to execute the Protractor E2E Test on a Bamboo Linux Build Server using XFVB for running Chrome or Chromium headless. The setup is similar to the one outlined in this gist: https://gist.github.com/nwinkler/f0928740e ...

What is the best way to stack three boxes on top of one another in Nextjs Tailwind?

Currently, I am working on creating a design with 3 boxes stacked vertically and then adding an image to it. You can see the example below: https://i.sstatic.net/jViO.png I have successfully implemented this layout, but I am facing an issue where the box ...

The image sits on the edge of the container, not fully contained

.sub2 { background-color: #FFFFBF; margin-top: 30px; height: 410px; width: 100%; } h1.sub2 { font: bold 100px american captain; text-decoration: underline; float: right; } p.sub2- { font: italic 25px american captain; margin-top: -300px; ...