单独文件名中的Python Selenium函数

2024-04-20 12:50:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个Python脚本,并希望将某些函数拆分为单独的文件,以便于维护。你知道吗

我现在有两个文件主.py和函数1.py

主.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)

函数1.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

我很确定这与我导入独立函数的方式有关,但无法找出问题所在,有人能帮忙吗?你知道吗


Tags: 函数frompyimportcomhttpurlexample
2条回答

您还必须将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)

我认为应该纠正一些代码:

第一次,删除^ {}之前的空白空间:

  #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):
    ...

相关问题 更多 >