fightstarr20
fightstarr20

Reputation: 12588

Python Selenium Function In Seperate File - NameError

I am building a Python script and want to split up certain functions into separate files to make maintenance easier.

I have two files currently called main.py and function1.py

main.pydef

#Setup Imports
import os
import os.path
import sys


# Import Functions
from function1 import myfunction


#Setup Selenium
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium import webdriver


#Launch Firefox
def init_driver():
    driver = webdriver.Firefox()
    return driver   

  url_list = ['http://www.example.com/page1', 'http://www.example.com/contact', 'http://www.example.com/about', 'http://www.example.com/test'];

driver = init_driver()

# Init Blank List
checked_urls = []

for url in url_list:
    myfunction(driver)

print(checked_urls)

function1.py

def myfunction(driver):

    driver.get(url)
    htmlText = driver.find_element_by_css_selector("#phrase").text

    if "This Is My Phrase" in htmlText:
        checked_urls.extend(['PHRASE_FOUND'])
    else:
        checked_urls.extend(['PHRASE_FOUND'])

I am trying to get it to visit each URL in the list and check for This Is My Phrase on the page. If it finds it then it should add to the list.

I am seeing the following error when running the script...

NameError: name 'url' is not defined

I am pretty sure it's related to the way I am importing the separate function but can't work out whats wrong, can anyone help?

Upvotes: 0

Views: 338

Answers (2)

yhlleo
yhlleo

Reputation: 13

I think some code should be corrected:

Frist, delete the blank space before url_list:

  #url_list = ['http://www.example.com/page1', 'http://www.example.com/contact', 'http://www.example.com/about', 'http://www.example.com/test'];
url_list = ['http://www.example.com/page1', 'http://www.example.com/contact', 'http://www.example.com/about', 'http://www.example.com/test'];

Then, the url is a local variable, it's not directly accessible in the function myfunction. But it can be accessed as a function parameter:

def myfunction(driver, url):
    ...

Upvotes: 1

Radek Kornik Wyka
Radek Kornik Wyka

Reputation: 50

You have to also pass url variable to myfunction:

def myfunction(driver, url):

    driver.get(url)
    htmlText = driver.find_element_by_css_selector("#phrase").text

    if "This Is My Phrase" in htmlText:
        checked_urls.extend(['PHRASE_FOUND'])
    else:
        checked_urls.extend(['PHRASE_FOUND'])

Then in main file:

for url in url_list:
    myfunction(driver, url)

Upvotes: 1

Related Questions