爬取广州天气并格式化输出

爬取广州未来七天天气情况,并格式化输出

网页情况

网页链接:http://www.weather.com.cn/weather/101280101.shtml

爬取红圈内情况
对于红圈内的天气情况,爬取并格式化输出。

网页源代码

在这里插入图片描述
F12进入开发者选项,查看网页源代码,定位到要爬取天气对应的源码位置。

代码

下面展示完整代码。

from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import re

html = urlopen("http://www.weather.com.cn/weather/101280101.shtml")
bs = BeautifulSoup(html,'html.parser')

try:
    
    def li(cl):
        a = []
        for i in cl:
            a.append(i.text.strip()) 
        return a

    date = bs.find_all("h1")[:7]  #日期
    wea = bs.find_all("p",class_="wea")    #天气情况
    tem = bs.find_all("p",class_="tem")    #气温
    win = bs.find_all("p",class_="win")    #风级

    n = []
    for i in win:
        n.append(i.find('span', class_ = re.compile('N'))['title'])  #风向
    # print(n)


    tplt = "{:8}\t{:8}\t{:10}\t{:10}\t{:10}" #格式化输出
    for i in range(7):
        print(tplt.format(li(date)[i],li(wea)[i],li(tem)[i],n[i],li(win)[i]),chr(12288))
        #chr(12288)指的是按照中文空格缩进
    print("爬取成功!!!")
except:
    print("爬取错误!!!")

输出结果

在这里插入图片描述

结束!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值