Python爬虫学习,抓取网页上的天气信息
来源:互联网 发布:时尚穿衣软件 编辑:程序博客网 时间:2024/04/30 13:43
今天学习了使用python编写爬虫程序,从中国天气网爬取杭州的天气。使用到了urllib库和bs4。bs4提供了专门针对html的解析功能,比用RE方便许多。
# coding : UTF-8import sysreload(sys)sys.setdefaultencoding( "utf-8" )from bs4 import BeautifulSoupimport csvimport urllibdef get_html(url): html = urllib.urlopen(url) return html.read()def get_data(html_text): final = [] bs = BeautifulSoup(html_text, "html.parser") body = bs.body data = body.find('div', {'id': '7d'}) ul = data.find('ul') li = ul.find_all('li') for day in li: temp = [] date = day.find('h1').string temp.append(date) inf = day.find_all('p') temp.append(inf[0].string,) if inf[1].find('span') is None: temperature_highest = None else: temperature_highest = inf[1].find('span').string temperature_highest = temperature_highest.replace('C', '') temperature_lowest = inf[1].find('i').string temperature_lowest = temperature_lowest.replace('C', '') temp.append(temperature_highest) temp.append(temperature_lowest) final.append(temp) return finaldef write_data(data, name): file_name = name with open(file_name, 'a') as f: f_csv = csv.writer(f) f_csv.writerows(data)if __name__ == '__main__': html_doc = get_html('http://www.weather.com.cn/weather/101190401.shtml') result = get_data(html_doc) write_data(result, 'weather.csv') print result
运行结果保存在csv文件中,如下:
28日(今天),小雨,,13℃29日(明天),小雨转阴,15℃,12℃30日(后天),多云,19℃,14℃31日(周一),小雨,16℃,14℃1日(周二),阴转多云,16℃,10℃2日(周三),多云转晴,17℃,10℃3日(周四),多云转晴,18℃,11℃
0 0
- Python爬虫学习,抓取网页上的天气信息
- 使用python抓取网页上的信息
- python3爬虫--抓取天气信息
- 【Python爬虫】批量抓取网页上的视频
- 爬虫:抓取某年某月某日某地的天气信息
- 抓取Foursquare网页信息的爬虫
- Python爬虫之抓取豆瓣信息 全部网页显示
- python——爬虫实现网页信息抓取
- python3爬虫--抓取网页信息
- [Python]网页信息抓取
- python爬虫:抓取页面上的超链接
- 抓取网页上的邮箱信息
- Python爬虫抓取网页图片
- python多线程爬虫抓取网页
- Python爬虫抓取网页图片
- python练习--天气信息抓取(1)
- Python爬虫学习笔记一:简单网页图片抓取
- Python抓取one网页上的内容
- iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD
- poj2195——Going Home(最小费用最大流)
- 【清华集训2014】mex
- 20161028 数字游戏
- sikulix document 学习笔记(二)——SikuliX是怎么运行的
- Python爬虫学习,抓取网页上的天气信息
- D3D11教程二十九之PlannarShadow(运用stencilBuffer)
- matplotlib
- 2016年10月28日,今天简单的工作总结
- 创建消息对话框的两种方式
- VIP课程共享
- NOIP 2008 传纸条
- neural turing machine:神经图灵机tensorflow源码注释
- python模块系列(三)之操作时间日期