python爬虫——简易天气爬取

通过爬虫,抓取http://www.weather.com.cn的天气信息

功能——输入城市代码,获取当日天气,简单的beautifulsoup和requests实现。(城市代码可百度查询,不全部展示)

代码如下:

from bs4 import BeautifulSoupimport requests


def get(city):
    citycode = {
    '北京': '101010100',
    '海淀': '101010200',
    '朝阳': '101010300',
    '顺义': '101010400',
    '怀柔': '101010500'
}
    try:
        url = 'http://www.weather.com.cn/weather/'+str(citycode[city])+'.shtml'
        res = requests.get(url)
        print(res)
        res.encoding='utf-8'
        soup = BeautifulSoup(res.text,'lxml')
        day = soup.select('li.on > h1')[0].string

        weather = soup.select('p.wea')[0].string

        tem = soup.select(' p.tem > i')[0].string

        wind= soup.select(' p.win > i')[0].string

        content = day+weather+tem+windexcept:
        content = "error"
    return content


city = raw_input()
get(city)

 

 

效果图:

转载于:https://www.cnblogs.com/vhills/p/7308158.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值