Home > Software engineering >  Turning This Weather Data Example Into A Loop?
Turning This Weather Data Example Into A Loop?

Time:12-09

Good Day,

I am a student in a intro to python class who is having a massive brain freeze on a project I'm working on. I've found a tutorial on weather data web scrapping online and have completed it. Although for my personal project with similar data, I want to create a loop where the user is allowed to keep inputting city names and get a return. But I can't figure out how to make it work :( Please help.

Weater Data Web-scrapping code:

from requests_html import HTMLSession

s = HTMLSession()

query = 'athens'
url = f'https://www.google.com/search?q=weather {query}'

r = s.get(url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'})

temp = r.html.find('span#wob_tm', first=True).text
unit = r.html.find('div.vk_bk.wob-unit span.wob_t', first=True).text
desc = r.html.find('div.VQF4g', first=True).find('span#wob_dc', first=True).text

print(query, temp, unit, desc)

For loop that kept resulting in error.

While look that kept resulting in error.

If else statements that didn't continue the loop.

CodePudding user response:

Use a while loop if you want run again and again. loops python

from requests_html import HTMLSession

s = HTMLSession()

while True: #Infinate loop
    
    query = input('Enter city: ')
    url = f'https://www.google.com/search?q=weather {query}'

    r = s.get(url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'})

    temp = r.html.find('span#wob_tm', first=True).text
    unit = r.html.find('div.vk_bk.wob-unit span.wob_t', first=True).text
    desc = r.html.find('div.VQF4g', first=True).find('span#wob_dc', first=True).text

    print(query, temp, unit, desc)

sample outputs #

Enter city: athens
athens 17 °C Partly cloudy
Enter city: newyork
newyork 11 °C Sunny
Enter city: 
  • Related