I'm very much a beginner to python, and I've been trying to figure this out for a few days. Hoping you guys can help me.
I'm looking to use the result of 'avail' in the below code determine whether to launch a batch file or not. For example, if the result is "YES" then run this batch file and end script. If the result is "NO" loop back and run again until "YES" is found.
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()
To answer the question:
# 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"
Next we would write the function that handles running the batch file.
def run_batch_file():
# I will leave this up to you to implement
Now your main function could look something like this:
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)
Since you are a python beginner, I have a comment regarding your code:
get_page
function, you only define soup
in the else clause. If the if
condition is true, soup will not be set, therefore return soup
will throw an error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.