Jan-20-2019, 02:27 PM
(This post was last modified: Jan-20-2019, 03:43 PM by ichabod801.)
Hello and good morning all.
I want to make it clear, I am not a programmer by any streach of the imagination. I just started trying to learn python a few days ago. My code works fine, but, it seems highly inefficient to me. As you can see I have opened and closed the same file 3 times to write too, and append my text file. I thought I could figure out a way to open the file just one time and write all the same data too it but I have failed.
Any thoughts or suggestions would be highly appreciated.
Have a great day.
I want to make it clear, I am not a programmer by any streach of the imagination. I just started trying to learn python a few days ago. My code works fine, but, it seems highly inefficient to me. As you can see I have opened and closed the same file 3 times to write too, and append my text file. I thought I could figure out a way to open the file just one time and write all the same data too it but I have failed.
Any thoughts or suggestions would be highly appreciated.
Have a great day.
#---- National Weather System by Python: from user_agent import generate_user_agent from bs4 import BeautifulSoup import requests headers = {'User-Agent': generate_user_agent(device_type='desktop', os=('mac', 'linux'))} # headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i686 on x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.63 Safari/537.36'} page_response = requests.get('https://forecast.weather.gov/MapClick.php?lat=32.47318000000007&lon=-100.40478999999999#.XC2EbM1MFEa/', timeout=5, headers=headers) soup = BeautifulSoup(page_response.content, 'html.parser') current = soup.find(id='current_conditions-summary') forecast = current.findAll(class_='myforecast-current') condition = forecast[0] period = current.find(class_='myforecast-current').get_text() temp_f = current.find(class_='myforecast-current-lrg').get_text() temp_c = current.find(class_='myforecast-current-sm').get_text() with open('C:\\Users\\user\\Documents\\Weather\\current-weather.txt', 'w') as f: print(period + '\n', temp_f + '\n', temp_c, file=f) table = soup.find('table') with open('C:\\Users\\user\\Documents\\Weather\\current-weather.txt', 'a') as f: for row in table.findAll('tr'): key = (' '.join(td.text.strip() for td in row.findAll('td'))) print(key, file=f) seven_day = soup.find(id='seven-day-forecast') forecast_items = seven_day.findAll(class_='tombstone-container') current = forecast_items[0] period = current.find(class_='period-name').get_text() short_desc = current.find(class_='short-desc').get_text() temp = current.find(class_='temp temp-high').get_text() with open('C:\\Users\\user\\Documents\\Weather\\current-weather.txt', 'a') as f: print(period + '\n', short_desc + '\n', temp, file=f)