Python小试牛刀之三

来源:互联网 发布:淘宝网百丽女鞋 编辑:程序博客网 时间:2024/05/16 15:36

天气预报的查询

  • 目的:用Python爬虫爬取中国天气网上4个城市未来7天的天气预报。
  • 方法:python爬虫
  • 工具包:random、requests、socket、time、http.client、csv和BeautufulSoup
  • 定义函数:spider_html();get_data();write_data();get_url()

其中工具包中random用于生成随机数,设定超时时间,防止被网站认为是爬虫;requests用于抓取网页的HTML源代码;time是获取时间日期;socket和http.client是做异常处理;csv用作文件数据(以excel的格式)的读取等操作;BeautifulSoup是用于代替正则获取源码相应标签的内容。

其中定义函数中spider_html()是爬取中国天气网页面的源代码;get_data()是获取HTML源代码中body部分中的列表有关天气的数据并做存储处理;write_data()将数据写入txt文件中;get_url()是获取相关城市(通过城市代码)天气的页面数据

城市代码可参考:
http://www.360doc.com/content/14/0322/07/59625_362614659.shtml

那么现在,我就开始放代码啦啦啦。。。

from bs4 import BeautifulSoup   import randomimport requests import socket import timeimport http.client import csvdef spider_html(url,data=None):    ##模拟浏览器来获取网页的html代码    header={        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',        'Accept-Encoding': 'gzip, deflate, sdch',        'Accept-Language': 'zh-CN,zh;q=0.8',        'Connection': 'keep-alive',        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'    }    timeout=random.choice(range(80,180))    while True:        try:            rep=requests.get(url,headers=header,timeout=timeout)            rep.encoding="utf-8"            break        except socket.timeout as e:            print("3:",e)            time.sleep(random.choice(range(8,15)))        except socket.error as e:            print("4:",e)            time.sleep(random.choice(range(20,60)))        except http.client.BadStatusLine as e:            print("5:",e)            time.sleep(random.choice(range(30,80)))        except http.client.IncompleteRead as e:            print("6:",e)            time.sleep(random.choice(range(5,15)))    return rep.textdef get_data(html_txt):    final=[]    bs=BeautifulSoup(html_txt,"html.parser")   #创建BeautifulSoup对象    body=bs.body   #获取body部分    data=body.find("div",{"id":"7d"}) #找到id为7d的div    ul=data.find("ul")  #获取ul部分    li=ul.find_all("li")   #获取所有的list    for day in li:          temp=[]        date=day.find("h1").string           temp.append(date)   #将日期存入到temp 中        inf=day.find_all("p")   #找到li中的所有p标签        temp.append(inf[0].string)   #将第一个p标签中的内容添加到temp列表中        if inf[1].find("span") is None:            temperature_high=None   #傍晚无最高气温        else:            temperature_high=inf[1].find("span").string  #最高气温            temperature_high=temperature_high.replace("℃","")        temperature_lower=inf[1].find("i").string   #最低温        temperature_lower=temperature_lower.replace("℃","")        temp.append(temperature_high)        temp.append(temperature_lower)        final.append(temp)       return finaldef write_data(data, name):    file_name = name    with open(file_name, 'a', errors='ignore', newline='') as f:            f_csv = csv.writer(f)            f_csv.writerows(data)def get_url():    city={    "嘉峪关":"101161401",    "杭州":"101230101",    "乐亭":"101090506",    "上海":"101020100"    }    for k in city:        print(k)    city_name=input("whitch city?:")    city_num=city[city_name]    weather_url="http://www.weather.com.cn/weather/%s.shtml"%city_num    return weather_urlif __name__=="__main__":    url=get_url()    html=spider_html(url)    result=get_data(html)    write_data(result,"weather.txt")    for i in result:        print(i)        

这是我的效果图:
这里写图片描述

这里写图片描述

Ps:此次我只写了能查询4个城市天气的功能,这个需要改进,写完了进PO上来了。

谢谢大家,欢迎交流指正!

0 0
原创粉丝点击