python爬虫项目之中国天气网的爬取终极版

说明:此项目替代了我们每天从网页或者其他途径上看全国各地的气温情况(本项目只是爬取的全国各个地区的最低气温,其他扩展功能根据此项目来完善即可!!!)

我们先看一下非常人性化的结果:

在这里插入图片描述用到的模块:

  1. requests
  2. pyecharts
  3. bs4

在这里必须说明一点(必做):我们用到的python版本基本上会在3.6以上,所以在用到pyecharts中的Bar时候会出现问题;为了解决这个问题,作者也有具体的解决步骤:升级版本:仅支持 Python3.6+

cmd命令下执行下面的三条:


1. pip install wheel
 
2. pip install pyecharts==0.1.9.4 或则 pip install pyecharts -U
 
3. pip install pyecharts-snapshot

注:引起这个问题是版本引起的,看了下官方的github发现的。

下面我们直接上完整代码:(具体操作的步骤会在后续文章中发出)

import requests
# from pyecharts import Bar
from bs4 import BeautifulSoup
from pyecharts import Bar
# 目标网站:http://www.weather.com.cn/textFC/hb.shtml

All_DATE=[]
def parse_url(url):
    headers = {
    
    'User-Agent':'此处需要更改成你本机的User-Agent'}
    reponse = requests.get(url,headers= headers)
    text = reponse.content.decode('utf-8')
    soup = BeautifulSoup(text, 'html5lib')
    ConMidtab  = soup.find('div',class_='conMidtab')
    # print(ConMidtab)
    tables = ConMidtab.find_all('table')
    for table in tables:
        # print(table)
        trs = table.find_all('tr')[2:]
        for index, tr in enumerate(trs):
            tds = tr.find_all('td')
            city_td = tds[0]
            if index==0:
                city_td = tds[1]
            city = list(city_td.stripped_strings)[0]
            tempt_td = tds[-2]
            min_tempt  = list(tempt_td.stripped_strings)[0]
            All_DATE.append({
    
    'city':city ,'min_tempt':int(min_tempt)})
    All_DATE.sort(key=lambda x: x['min_tempt'])
    data = All_DATE[0:20]  # 取出前20个
    cities = list(map(lambda x: x['city'],data))
    tempts = list(map(lambda x: x['min_tempt'], data))
    # plt.bar(cities, tempts,color ='r')  # 绘制柱状图
    # plt.show('mytempt.html')
    # print(cities)
    # print(tempts)
    chart = Bar("实时动态华北地区的最低气温柱状图")
    chart.add("",cities,tempts)
    chart.render('实时天气.html')


def get_url():
    urls = ['http://www.weather.com.cn/textFC/hb.shtml',
          'http://www.weather.com.cn/textFC/db.shtml',
          'http://www.weather.com.cn/textFC/hd.shtml',
          'http://www.weather.com.cn/textFC/hz.shtml',
          'http://www.weather.com.cn/textFC/hn.shtml',
          'http://www.weather.com.cn/textFC/xb.shtml',
          'http://www.weather.com.cn/textFC/xn.shtml',
          'http://www.weather.com.cn/textFC/gat.shtml'
          ]
    for url in urls:
        parse_url(url)
        break    # 为了节省时间我们只获取了第一个华北地区的最低气温情况


if __name__ == '__main__':
    get_url()

结果也会正常的显示!

猜你喜欢

转载自blog.csdn.net/m0_48915964/article/details/115576168