如何在函数中使用LOCAL VARIABLE,例如其他函数的GLOBAL VARIABLE变量

时间:2019-01-09 12:59:56

标签: python selenium global-variables sendmail smtplib

我在selenium上编写了一个简单的测试,该测试在某些站点上进行身份验证,对HTML代码的某些部分进行解析并将电子邮件发送到所需的邮箱。我想使一切变得美丽,因此决定为该代码定义函数。

我的代码:

from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import smtplib

CHROME_PATH = '/usr/bin/google-chrome'
CHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'
WINDOW_SIZE = "1024,768"

def pgi_auth(sitename, region_pgi, login_pgi, password_pgi):
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
    chrome_options.binary_location = CHROME_PATH
    driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,chrome_options=chrome_options)
    driver.get(sitename)
    driver.find_element_by_id("LoginId").send_keys(login_pgi)
    driver.find_element_by_id("LoginPassword").send_keys(password_pgi)

    option = Select(
        driver.find_element_by_xpath("//select[@name='Region']")
    ).select_by_value(region_pgi)

    driver.find_element_by_id("submit").click()

    element = driver.find_element_by_id("TotalCurrentCharges-body").text

    current_charges = element.splitlines()[1]
    print(current_charges)
    driver.quit()

def send_email(host, port, from_addr, password, to_addr, subject, current_charges):
    BODY = "\r\n".join((
        "From: %s" % from_addr,
        "To: %s" % to_addr,
        "Subject: %s" % subject ,
        "",
        body_text
    ))
    server = smtplib.SMTP(host, port)
    server.starttls()
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], BODY)
    server.quit()

#for pgi_auth
sitename="https://invoiceaccess.pgiconnect.com"
login_pgi="my_secret_login"
password_pgi="my_secret_password"
region_pgi="us"

#for send_email
host = "mail.example.com"
port = "587"
from_addr = "test.mail@example.com"
password = "my_secret_password"
to_addr = "test.receive@example.com"
subject = "MY BALANCE:"

pgi_auth(sitename, region_pgi, login_pgi, password_pgi)
send_email(host, port, from_addr, password, to_addr, subject, current_charges)

在函数pgi_auth中,我收到变量current_charges 我想在功能pgi_auth的{​​{1}}之外使用此变量。当然,我可以在不使用函数的情况下实现此功能,但是我想尝试使所有内容变得美观(也许我将使用config),如何在函数外获取此变量?

1 个答案:

答案 0 :(得分:1)

您需要在方法中使用return关键字

def pgi_auth(sitename, region_pgi, login_pgi, password_pgi):
    .....
    .....
    return current_charges

....
....
subject = "MY BALANCE:"

current_charges = pgi_auth(sitename, region_pgi, login_pgi, password_pgi)
send_email(host, port, from_addr, password, to_addr, subject, current_charges)