簡體   English   中英

如何使用“get_detail_data”的output運行批處理文件

[英]How to use the output of “get_detail_data” to run batch file

我是 python 的初學者,幾天來我一直在努力解決這個問題。 希望你們能幫助我。

我希望在下面的代碼中使用“avail”的結果來確定是否啟動批處理文件。 例如,如果結果為“YES”,則運行此批處理文件並結束腳本。 如果結果為“NO”,則返回並再次運行,直到找到“YES”。

import  requests
from bs4 import BeautifulSoup

def get_page(url):
    response = requests.get(url)

    if not response.ok:
        print('Server responded:', response.status_code)
    else:
        soup = BeautifulSoup(response.text, 'lxml')
    return soup

def get_detail_data(soup):

    avail = soup.find('span', id='availability').text.strip()
    print(avail)

def main():
    url ='https://www.blahblah.com'

    get_detail_data(get_page(url))

if __name__ == '__main__':
    main()

要回答這個問題:

# Here is one way we could implement get_detail_data (its a bit verbose)
def get_detail_data(soup):
    avail = soup.find('span', id='availability').text.strip()
    if avail == "YES":
        return True
    elif avail == "NO":
        return False
    else: 
        print("Unexpected value")
        return None

# Or a slightly cleaner way (returns True if and only if avail == "YES"
def get_detail_data(soup):
    avail = soup.find('span', id='availability').text.strip()
    return avail == "YES"

接下來我們將編寫處理運行批處理文件的 function。

def run_batch_file():
    # I will leave this up to you to implement

現在您的主要 function 可能看起來像這樣:

def main():
    url ='https://www.blahblah.com'

    # This is how we create an infinite loop in python
    while True:
        # check to see if its available
        is_available = get_detail_data(get_page(url))
        if is_available:
            # if its available, we run the batch file, then break out of the loop
            # (It might help to read up on loops, and the break keyword in python)
            run_batch_file()
            break
        
        # if the program gets to this line, then is_available was false
        #   so we will wait for a little bit before checking again
        #   (it might help to read up on time.sleep)
        time.sleep(10)    

由於您是 python 初學者,我對您的代碼有一個評論:

  • get_page function 中,您只需在 else 子句中定義soup 如果if條件為真,則不會設置湯,因此return soup會拋出錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM