Python captures the PM2.5 concentration and ranking of cities, and pythonpm2.5

Source: Internet
Author: User

Python captures the PM2.5 concentration and ranking of cities, and pythonpm2.5

Host environment: (Python2.7.9/Win8_64/bs4)

BeautifulSoup4 is used to capture PM2.5 data on www.pm25.com. The reason why this website is crawled is because of the ranking of PM2.5 concentration in cities. (the real reason is that it is the first website that Baidu has searched for PM2.5 !)

The program only compares the two cities, so the speed of multi-threading is not very obvious. You can try it in 10 cities and start 10 threads.

Finally, let's talk about the poor air quality in Shanghai !!!

PM25.py

Copy codeThe Code is as follows:
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
# By ustcwq
Import urllib2
Import threading
From time import ctime
From bs4 import BeautifulSoup
Def getPM25 (cityname ):
Site = 'HTTP: // www.pm25.com/'+ cityname + '.html'
Html = urllib2.urlopen (site)
Soup = BeautifulSoup (html)
City = soup. find (class _ = 'bi _ loaction_city ') # city name
Aqi = soup. find ("a", {"class", "bi_aqiarea_num"}) # AQI Index
Quality = soup. select (". bi_aqiarea_right span") # Air quality Grade
Result = soup. find ("div", class _ = 'bi _ aqiarea_bottom ') # air quality description
Print city. text + u'aqi index: '+ AQI. text + U' \ n air quality:' + quality [0]. text + result. text
Print '* 20 + ctime () +' * 20
Def one_thread (): # single thread
Print 'one _ thread Start: '+ ctime () +' \ N'
GetPM25 ('hefei ')
GetPM25 ('shanghai ')
Def two_thread (): # Multithreading
Print 'two _ thread Start: '+ ctime () +' \ N'
Threads = []
T1 = threading. Thread (target = getPM25, args = ('hefei ',))
Threads. append (t1)
T2 = threading. Thread (target = getPM25, args = ('shanghai ',))
Threads. append (t2)
For t in threads:
# T. setDaemon (True)
T. start ()
If _ name _ = '_ main __':
One_thread ()
Print '\ n' * 2
Two_thread ()

The above is all the content described in this article. I hope you will like it.

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.