如何修复从另一个文件调用函数时的NameError



我想使用selenium和未检测到的chromedriver登录Gmail。使用这些代码成功登录。我的gmail_login.py文件代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import undetected_chromedriver.v2 as uc
if __name__ == '__main__':
options = uc.ChromeOptions()
options.add_argument("--ignore-certificate-error")
options.add_argument("--ignore-ssl-errors")
# e.g. Chrome path in Mac =/Users/x/Library/xx/Chrome/Default/
# options.add_argument( "--user-data-dir=<Your chrome profile>")
driver = uc.Chrome(options=options)
url='https://accounts.google.com/servicelogin'
driver.get(url)
# add email
driver.find_element(By.XPATH, '//*[@id="identifierId"]').send_keys(gmail_uid)
driver.find_element(By.XPATH, '//*[@id="identifierNext"]/div/button/span').click()

driver.find_element(By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input').send_keys(gmail_pwd)
driver.find_element(By.XPATH, '//*[@id="passwordNext"]/div/button/span').click()

def my_custom_function(url):
get_url = driver.get(url)
return get_url

但是当我试图从另一个python文件调用我的my_custom_function(url)时,得到了NameError。我的新文件.py看起来像

from gmail_login import *
print(my_custom_function('https://google.com')) 
NameError: name 'my_custom_function' is not defined

我假设此NameError提升用于此if __name__ == '__main__':压痕

我该如何解决这个问题?这两个文件都在同一个文件夹中。

使用if __name__ == "__main__":为您的项目提供了一个入口点,通常在您有多个文件并希望指定运行项目时会发生什么时使用。

进一步阅读:https://www.freecodecamp.org/news/if-name-main-python-example/

因此,一旦执行了gmail_login.py文件,所有的代码、变量和函数(如my_custom_function(声明都会运行。这就是为什么它说它没有定义。该怎么办?您可以在if语句上面定义您的函数,然后在if语句中调用它,并将其导入到您想要的任何位置。希望它能有所帮助!

很快就可以像我举的例子一样重构你的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import undetected_chromedriver.v2 as uc
def get_driver():
options = uc.ChromeOptions()
options.add_argument("--ignore-certificate-error")
options.add_argument("--ignore-ssl-errors")
# e.g. Chrome path in Mac =/Users/x/Library/xx/Chrome/Default/
# options.add_argument( "--user-data-dir=<Your chrome profile>")
driver = uc.Chrome(options=options)
url='https://accounts.google.com/servicelogin'
driver.get(url)
# add email
driver.find_element(By.XPATH, '//*[@id="identifierId"]').send_keys(gmail_uid)
driver.find_element(By.XPATH, '//*[@id="identifierNext"]/div/button/span').click()

driver.find_element(By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input').send_keys(gmail_pwd)
driver.find_element(By.XPATH, '//*[@id="passwordNext"]/div/button/span').click()
return driver
def my_custom_function(url):
driver = get_driver()
get_url = driver.get(url)
return get_url
if __name__ == "__main__":
my_custom_function()

最新更新