943,922 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 2415
  • Python RSS
Sep 8th, 2009
0

Searching Weather for a term with urllib2 module

Expand Post »
Hey guys,

I am making a program called 'Weather Watch' which basically gets weather updates for any city you type in.

For now, it only gets info for a particular city. I don't know how to search for the term entered in www.weather.com and then get the updates. The code so far:
python Syntax (Toggle Plain Text)
  1. import urllib2 as url
  2. import os
  3. import time
  4.  
  5. os.system('cls')
  6.  
  7. print("[Content provided by The Weather Channel]")
  8. time.sleep(3)
  9. os.system('cls')
  10.  
  11. print("Please wait...this may take a few seconds.")
  12. time.sleep(3)
  13. os.system('cls')
  14.  
  15. condition=True
  16.  
  17. try:
  18. url_open=url.urlopen("http://www.weather.com")
  19. lines=url_open.readlines()[1192:1199]
  20. except:
  21. condition=False
  22.  
  23. if(condition):
  24. print("Weather forecast for Bangalore, INDIA\n")
  25. for x in lines:
  26. onsplit=x.split(">")
  27.  
  28. tags=onsplit[2][:-5]
  29.  
  30. if(tags=="Pressure:"):
  31. data=onsplit[4][:5]
  32. elif(tags=="Dew Point:"):
  33. data=onsplit[4][:2]
  34. else:
  35. data=onsplit[4][:-5]
  36.  
  37. print(tags+" "+data)
  38. raw_input("\n<Any key to quit>")

This is what I've learnt on searching for a term in a site[Google, here]

python Syntax (Toggle Plain Text)
  1. import urllib2 as url2
  2. import urllib as url
  3.  
  4. values={"search":"city"}
  5.  
  6. data=url.urlencode(values)
  7.  
  8. req=url2.Request("http://www.google.com",data)
  9. res=url2.urlopen(req)
  10.  
  11. print(res.read())
Similar Threads
Reputation Points: 2
Solved Threads: 30
Posting Whiz in Training
sravan953 is offline Offline
242 posts
since May 2009
Sep 8th, 2009
0

Re: Searching Weather for a term with urllib2 module

Both weather.com and google have APIs for accessing weather info. Basically, you form a URL in a specified format and get and XML page with current weather and forecasts. Weather.com requires signing up in advance, at no cost.

http://www.weather.com/services/xmloap.html
A google example:
http://www.google.com/ig/api?weather=New%20York

There are a bunch of python examples out there. You have to parse XML, but it's pretty easy.
Reputation Points: 10
Solved Threads: 2
Light Poster
foosion is offline Offline
31 posts
since Jul 2009
Sep 8th, 2009
0

Re: Searching Weather for a term with urllib2 module

foosion, I did not understand you fully. On what format is the URL formed? If I get the URL right for all cities, I can take care of 'getting' the data, by slicing and so on. So, how is the URL formed?
Reputation Points: 2
Solved Threads: 30
Posting Whiz in Training
sravan953 is offline Offline
242 posts
since May 2009
Sep 8th, 2009
0

Re: Searching Weather for a term with urllib2 module

It depends on which service you use and what info you want.

Here's an example for google (and yahoo and noaa) weather. It was the first hit when I used google to search for "python weather google." http://code.google.com/p/python-weather-api/
Reputation Points: 10
Solved Threads: 2
Light Poster
foosion is offline Offline
31 posts
since Jul 2009
Sep 8th, 2009
0

Re: Searching Weather for a term with urllib2 module

Following the thinking of sneekula at:
http://www.daniweb.com/forums/post89...tml#post892908
You can do some detective work and pull weather data from the www.weather.com html code like my little example shows ...
python Syntax (Toggle Plain Text)
  1. # given the zip code, extract the weather conditions of the area
  2. # tested with Python25
  3.  
  4. import urllib2
  5. import time
  6.  
  7. def extract(text, sub1, sub2):
  8. """
  9. extract a substring from text between first
  10. occurances of substrings sub1 and sub2
  11. """
  12. return text.split(sub1, 1)[-1].split(sub2, 1)[0]
  13.  
  14.  
  15. zipcode = '91201'
  16. url_str = 'http://www.weather.com/weather/local/' + zipcode
  17. try:
  18. fin = urllib2.urlopen(url_str)
  19. html = fin.readlines()
  20. fin.close()
  21. except IOError:
  22. print( 'Cannot open URL %s for reading' % url_str )
  23. html = False
  24.  
  25. if html:
  26. for line in html:
  27. #print( line ) # test
  28. if line.startswith('OAS_spoof'):
  29. location = line
  30. if line.startswith('OAS_query'):
  31. weather = line
  32.  
  33. #print( location ) # test
  34. #print( weather ) # test
  35.  
  36. location_list = location.split('/')
  37. #print( location_list ) # test
  38.  
  39. town = location_list[9].capitalize()
  40. state = location_list[7].capitalize()
  41. zip = location_list[10][:5]
  42.  
  43. print( time.strftime("%A, %d%b%Y at %H:%M hours", time.localtime()) )
  44. print( "Lovely %s, %s %s" % (town, state, zip) )
  45.  
  46. temp_now = extract(weather, 'temp=', '&')
  47. cond_now = extract(weather, 'cond=', '&')
  48. temp_high = extract(weather, 'temph1=', '&')
  49. temp_low = extract(weather, 'templ1=', '&')
  50.  
  51. sf = "is %s with %sF (low=%sF and high=%sF)"
  52. print( sf % (cond_now, temp_now, temp_low, temp_high) )
  53.  
  54. """my result -->
  55. Tuesday, 08Sep2009 at 13:15 hours
  56. Lovely Glendale, Ca 91201
  57. is clear_sunny with 81F (low=62F and high=84F)
  58. """
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 10th, 2009
1

Re: Searching Weather for a term with urllib2 module

I did something very similar for my father who happens to be a weather nut. I went online and found the webpage for our zipcode and used urllib to get updates of the webpage every 15 minutes or so. Then I just parsed the html for common things like temperature, dew point, cloud coverage. It was pretty simple once you knew what to look for. My solution worked fine for me but if you plan on sharing this program with more than you or maybe a family member I would recomend using the APIs as they will probably be more reliable. If the weather channel were to change their webpage design my little program could be useless.

--EAnder
Reputation Points: 26
Solved Threads: 5
Light Poster
EAnder is offline Offline
49 posts
since Feb 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: pygame and opengl
Next Thread in Python Forum Timeline: complicated file parsing





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC