Python3 crawls various weather information and python3 crawls the weather

Source: Internet
Author: User

Python3 crawls various weather information and python3 crawls the weather

I was looking for a crawler program on the Internet to find out whether there is a ready-made crawler program that crawls Air Quality Conditions and weather conditions. I thought I 'd write it for a while.

It mainly crawls air quality data and weather data from Beijing, including provincial capitals around Beijing.

An error occurs: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 250.

It turns out that the page encoding is gbk. Change the statement to data = urllib. request. urlopen (url). read (). decode ("gbk.

Then I wrote the crawled data to the text document, which can be imported to an excel table later.

The computer in the lab is not always on, and then it is put on the server. Let it crawl for an hour ~ Hahaha ~

An exception occurred one night later. Because no exception processing was added, the data from to AM was not crawled...

Then the modification adds exception handling. If URLError appears, try again in one minute.

Code:

# Coding = UTF-8 # import urllib to the hourly Monitoring Value crawler program for pollution data and weather data in Beijing and surrounding provincial capitals. request import re import urllib. error import time # simulate the browser headers = ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) chrome/45.0.2454.101 Safari/537.36 ") opener = urllib. request. build_opener () opener. addheaders = [headers] # Install opener as global urllib. request. install_opener (opener) def get_pm25_and_weather (city): # First obtain the air quality data, and return the data update time data_time = getpm25 (city) # then assign the obtained data update time to the weather data retrieval function using getweather (city, data_time) def getpm25 (city): try: # Set url = "http://pm25.in/" + city data = urllib. request. urlopen (url ). read (). decode ("UTF-8") print ("city:" + city) # expression for building the data update time data_time = '<div class = "live_data_time"> \ s {1 ,} <p> Data Update Time :(. *?) </P> '# Find the data update time datatime = re. compile (data_time, re. S ). findall (data) print ("data Update time:" + datatime [0]) # construct the data collection expression data_pm25 = '<div class = "span1"> \ s {1,} <div class = "value" >\n \ s {1 ,} (. *?) \ S {1 ,}</div> 'data_o3 = '<div class = "span1"> \ s {1 ,} <div class = "value"> \ n \ s {1 ,}(. *?) \ S {1 ,}</div> '# Find all monitoring values pm25list = re. compile (data_pm25, re. S ). findall (data) o3list = re. compile (data_o3, re. S ). findall (data) # Insert the hourly ozone value to the original pm25list. append (o3list [0]) print ("AQI index, PM2.5, PM10, CO, NO2, SO2, O3 :( unit: μg/m3, CO is mg/m3 )") print (pm25list) # Write the obtained value to the writefiles_pm25 (city, datatime, pm25list) # return the data update time value return datatime release T urllib. error. URLError as e: print ("URLERROR! Try again in one minute ...... ") If hasattr (e," code "): print (e. code) if hasattr (e, "reason"): print (e. reason) time. sleep (60) # If an Exception occurs, run the getpm25 (city) failed t EXCEPTION as e: print ("Exception! Try again in 10 seconds ...... ") Print (" Exception: "+ str (e) time. sleep (10) # If an exception occurs, run this part again later. getpm25 (city) def writefiles_pm25 (filename, datatime, pm25list): # Write the obtained data to the file, the data are time, AQI index, PM2.5, PM10, CO, NO2, SO2, and O3 respectively. (Unit: μ g/m3, CO is mg/m3) f = open ("D: \ Python \ Python35 \ myweb \ data_pm25 \ data_pm25 _" + filename + ". txt "," a ") f. write (datatime [0]) f. write (",") for pm25 in pm25list: f. write (str (pm25) f. write (",") f. write ("\ n") print ("this air quality data has been added to the file! ") F. close () def getweather (city, datatime): try: # construct url = "http: //" + city + ".tianqi.com/" data = urllib. request. urlopen (url ). read (). decode ("gbk") # construct the data collection expression data_weather = '<li class = "cDRed"> (. *?) </Li> 'data_wind = '<li style = "height: 18px; overflow: hidden"> (.*?) </Li> 'data_temperature = '<div id = "rettemp"> <strong> (.*?) ° 'Data_humidity = '</strong> <span> relative humidity :(.*?) </Span> '# Find all monitoring values weatherlist = re. compile (data_weather, re. S ). findall (data) windlist = re. compile (data_wind, re. S ). findall (data) temperaturelist = re. compile (data_temperature, re. S ). findall (data) humiditylist = re. compile (data_humidity, re. S ). findall (data) # insert other values to the weatherlist in the weather list. append (windlist [0]) weatherlist. append (temperaturelist [0]) weatherlist. append (humiditylist [0]) print ("weather condition, wind direction, wind speed, real-time temperature, Relative humidity: ") print (weatherlist) # Write the obtained value to the writefiles_weather (city, datatime, weatherlist) file before t urllib. error. URLError as e: print ("URLERROR! Try again in one minute ...... ") If hasattr (e," code "): print (e. code) if hasattr (e, "reason"): print (e. reason) time. sleep (60) # If an Exception occurs, run the getweather (city, datatime) failed t EXCEPTION as e: print ("Exception! Try again in 10 seconds ...... ") Print (" Exception: "+ str (e) time. sleep (10) # If an exception occurs, run this part again later. getweather (city, datatime) def writefiles_weather (filename, datatime, weatherlist): # Write the obtained data to the file, the data includes time, weather conditions, wind direction, wind speed, real-time temperature, and relative humidity. F = open ("D: \ Python \ Python35 \ myweb \ data_weather _" + filename + ". txt "," a ") f. write (datatime [0]) f. write (",") for weather in weatherlist: f. write (str (weather) f. write (",") f. write ("\ n") print ("this weather data has been added to the file! ") F. close () # exit the loop. Ctrl + C can be used. while True: print (" starts to work! ") Aggregate (" beijing ") get_pm25_and_weather (" tianjin ") aggregate (" shijiazhuang ") aggregate (" taiyuan ") aggregate (" jinan ") aggregate (" shenyang ") get_pm25_and_weather ("huhehaote") get_pm25_and_weather ("zhengzhou") # execute print ("break ...... ") Print (" \ n ") time. sleep (3600)

Running status chart:

For more information, see the topic "python crawling function summary.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.