不确定为什么if语句的“ else”无法正常工作

时间:2019-12-30 03:53:46

标签: python if-statement tkinter beautifulsoup

我正在使用BeautifulSoup / requests和Tkinter从Yahoo Finances网上抓取股票价值。如果用户在GUI输入框中键入单词,我将程序设置为刮取值,其他所有内容都应返回“未找到”。

但是,有一个问题。我的程序正确地遵循了if语句,但是使用“ else”则无法更新。花了一段时间浏览我的代码后,我不确定为什么会这样。

如果有人可以帮助我,我将不胜感激!

from bs4 import BeautifulSoup
import requests
import tkinter

headers = {"User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) Apple Webkit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15"}


# *** Functions pertaining to the GUI application ***

# Resets the data fields after submission
def ResetData():
    user_company.delete('0', 'end')

#  *** Functions pertaining to the web scraping of Yahoo Finances ***

def ChooseValue():
    global output_value

    try:
        if user_company.get().upper() == "DOW JONES":
            getDOW()
        elif user_company.get().upper() == "APPLE":
            getApple()
        elif user_company.get().upper() == "NASDAQ":
            getNASDAQ()
        elif user_company.get().upper() == "S&P 500":
            getSP()
        else:
            output_value.config(text = "Not Found!", fg = "green")

    except Exception:
        output_value.config(text = "ERROR!", fg = "red")

    output_value.config(text = "$" + str(value), fg = "blue")
    ResetData()

# Extracts the DOW Jones Industrial Average
def getDOW():
    global value
    URL = "https://finance.yahoo.com/quote/^DJI?p=^DJI"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Exracts NASDAQ index 
def getNASDAQ():
    global value
    URL = "https://finance.yahoo.com/quote/^IXIC?p=^IXIC"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Extracts S&P 500 index
def getSP():
    global value
    URL = "https://finance.yahoo.com/quote/^GSPC?p=^GSPC"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Extracts Apple Inc. (AAPL)
def getApple():
    global value
    URL = "https://finance.yahoo.com/quote/AAPL?p=AAPL"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

def main():
    global user_company, output_value

    window = tkinter.Tk()
    window.title("Stock Value Search")

    output_value = tkinter.Label(window, text = "             ", fg = "blue")
    output_value.pack()

    user_company_label = tkinter.Label(window, text = "Enter company/index: ")
    user_company_label.pack()

    user_company = tkinter.Entry(window)
    user_company.pack()

    processButton = tkinter.Button(window, text = "Search", command = ChooseValue)
    processButton.pack()

    window.mainloop()

main()

4 个答案:

答案 0 :(得分:0)

在其他情况下,push的倒数第二行将覆盖您在ChooseValue中写的内容。

答案 1 :(得分:0)

在您的def ChooseValue():方法中:无论if / elif / else块还是try / except块的结果,最后一行总是始终运行。

# This is always run and overwites any previous calls
output_value.config(text = "$" + str(value), fg = "blue")

您应将此行添加到try / except的else块中,以便仅在至少没有异常的情况下运行

except Exception:
    output_value.config(text = "ERROR!", fg = "red")
else:
    output_value.config(text = "$" + str(value), fg = "blue")

如果您从if / else块的“未找到”分支返回并将对ResetData()的调用添加到最终的集团中,您应该会得到所需的行为

 def ChooseValue():
     global output_value

     try:
         if user_company.get().upper() == "DOW JONES":
             getDOW()
         elif user_company.get().upper() == "APPLE":
             getApple()
         elif user_company.get().upper() == "NASDAQ":
             getNASDAQ()
         elif user_company.get().upper() == "S&P 500":
             getSP()
         else:
             print('else run')
             output_value.config(text = "Not Found!", fg = "green")
             return
    except Exception:
        output_value.config(text = "ERROR!", fg = "red")
    else:
        # This only gets executed when an exception is not raised or a return/continue/break is not used
        output_value.config(text = "$" + str(value), fg = "blue")
    finally:
        # Always gets run, even when something "returns"
        ResetData()

答案 2 :(得分:0)

实际上,它可以运行。您可以添加打印件以查看它。然后您应该返回else块。

from bs4 import BeautifulSoup
import requests
import tkinter

headers = {"User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) Apple Webkit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15"}


# *** Functions pertaining to the GUI application ***

# Resets the data fields after submission
def ResetData():
    user_company.delete('0', 'end')

#  *** Functions pertaining to the web scraping of Yahoo Finances ***

def ChooseValue():
    global output_value

    try:
        if user_company.get().upper() == "DOW JONES":
            getDOW()
        elif user_company.get().upper() == "APPLE":
            getApple()
        elif user_company.get().upper() == "NASDAQ":
            getNASDAQ()
        elif user_company.get().upper() == "S&P 500":
            getSP()
        else:
            print('else run')
            output_value.config(text = "Not Found!", fg = "green")
            return

    except Exception:
        output_value.config(text = "ERROR!", fg = "red")

    output_value.config(text = "$" + str(value), fg = "blue")
    ResetData()

# Extracts the DOW Jones Industrial Average
def getDOW():
    global value
    URL = "https://finance.yahoo.com/quote/^DJI?p=^DJI"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Exracts NASDAQ index 
def getNASDAQ():
    global value
    URL = "https://finance.yahoo.com/quote/^IXIC?p=^IXIC"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Extracts S&P 500 index
def getSP():
    global value
    URL = "https://finance.yahoo.com/quote/^GSPC?p=^GSPC"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Extracts Apple Inc. (AAPL)
def getApple():
    global value
    URL = "https://finance.yahoo.com/quote/AAPL?p=AAPL"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

def main():
    global user_company, output_value

    window = tkinter.Tk()
    window.title("Stock Value Search")

    output_value = tkinter.Label(window, text = "             ", fg = "blue")
    output_value.pack()

    user_company_label = tkinter.Label(window, text = "Enter company/index: ")
    user_company_label.pack()

    user_company = tkinter.Entry(window)
    user_company.pack()

    processButton = tkinter.Button(window, text = "Search", command = ChooseValue)
    processButton.pack()

    window.mainloop()

main()```

答案 3 :(得分:0)

尝试在user_company.get().upper()语句之前将if转换为字符串,并将其保存到变量中。

赞:

variable = str(user_company.get().upper())
if variable == "DOW JONES":
     getDOW()
elif variable == "APPLE":
     getApple()
elif variable == "NASDAQ":
     getNASDAQ()
elif variable == "S&P 500":
     getSP()
else:
     print('else run')
     output_value.config(text = "Not Found!", fg = "green")
     return