2016-02-25 29 views
0

我正在構建一個Python腳本,並希望將某些函數分解爲單獨的文件以使維護更容易。在單獨文件中的Python Selenium函數 - NameError

我目前叫main.py和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']) 

我試圖得到兩個文件它訪問列表中的每個URL並檢查這是我的短語在頁面上。如果發現它,它應該添加到列表中。

我運行腳本時看到下面的錯誤...

NameError: name 'url' is not defined 

我敢肯定它關係到我導入獨立的功能,但什麼是錯不能工作的出路,任何人都可以幫幫我?

+1

這不是關於導入!試着把你的'myfunction()'作爲獨立的函數......沒有變量叫做'url'。我想你應該添加'url'到函數args:'myfunction(driver,url)' – Andersson

回答

1

你也必須通過url變量給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']) 

然後在主文件:

for url in url_list: 
    myfunction(driver, url) 
+0

這很有道理,我是否也需要通過checked_urls? – fightstarr20

+2

你最好在'myfunction()'內部聲明'checked_urls = []'並讓它'返回checked_urls' – Andersson

1

我覺得有些代碼應該予以糾正:

弗里斯特,刪除空白太空前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']; 

然後,url是一個局部變量,它不能在函數myfunction中直接訪問。但它可以作爲函數參數訪問:

def myfunction(driver, url): 
    ... 
相關問題