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)

 

 

效果图:

posted on 2017-08-08 17:52  vhills  阅读(506)  评论(0编辑  收藏  举报