树莓派 相比 Arduino 主板,他提供了以太网接口,你也可以通过使用廉价的USB WiFi模块来实现无线网络,另外因为树莓派基于Linux操作系统,在网络应用项目编程方面更易于实现。下面咱们试试使用Python来实现网络功能。我们将树莓派作为客户端来访问服务器,建立链接。首先我们来安装 Requests 这个Python库,Requests库提供了通过HTTP向Web服务器发送请求的功能。安装完毕后,我们导入模块测试是否安装成功:root@raspberrypi:/home/pi# apt-get install python-requestsroot@raspberrypi:/home/pi# pythonPython 2.7.3 (default, Jan 13 2013, 11:20:46) [GCC 4.6.3] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import requests>>> 然后我们尝试和 www.dfrobot.com 网站建立链接:>>> r = requests.get('http://www.dfrobot.com/')>>> r.status_code200>>>获得的所有数据已经保存在r对象中,r.status_code 是请求的返回码,200代表 正常你也可以察看服务器返回的内容:>>> r.text将会得到一大串文本,这是 www.dfrobot.com 网站首页的HTML代码。接下来我们访问中央气象局的网站获得当地的气象信息。首先需要查询本地的代码:获取省份代码http://m.weather.com.cn/data5/city.xmlXML 解析错误:语法错误位置:http://m.weather.com.cn/data5/city.xml行 1,列 1:01|北京,02|上海,03|天津,04|重庆,05|黑龙江,06|吉林,07|辽宁,08|内蒙古,09|河北,10|山西,11|陕西,12|山东,13|新疆,14|西藏,15|青海,16|甘肃,17|宁夏,18|河南,19|江苏,20|湖北,21|浙江,22|安徽,23|福建,24|江西,25|湖南,26|贵州,27|四川,28|广东,29|云南,30|广西,31|海南,32|香港,33|澳门,34|台湾^四川的省代码为27将27加入网址访问,获取城市列表http://m.weather.com.cn/data5/city27.xmlXML 解析错误:语法错误位置:http://m.weather.com.cn/data5/city27.xml行 1,列 1:2701|成都,2702|攀枝花,2703|自贡,2704|绵阳,2705|南充,2706|达州,2707|遂宁,2708|广安,2709|巴中,2710|泸州,2711|宜宾,2712|内江,2713|资阳,2714|乐山,2715|眉山,2716|凉山,2717|雅安,2718|甘孜,2719|阿坝,2720|德阳,2721|广元^成都的代码是2701,接着我们查询成都市的 地区代码:http://m.weather.com.cn/data5/city2701.xmlXML 解析错误:语法错误位置:http://m.weather.com.cn/data5/city2701.xml行 1,列 1:270101|成都,270102|龙泉驿,270103|新都,270104|温江,270105|金堂,270106|双流,270107|郫县,270108|大邑,270109|蒲江,270110|新津,270111|都江堰,270112|彭州,270113|邛崃,270114|崇州,270115|青白江^温江区代码为270104,输入以下连接查询:http://m.weather.com.cn/data5/city270104.xmlXML 解析错误:语法错误位置:http://m.weather.com.cn/data5/city270104.xml行 1,列 1:270104|101270104^在这里查询到四川省成都市温江区的地区代码 101270104将代码加入到天气查询里面,输入以下3个网址的任意一个得到不同的天气JSON格式的信息。http://www.weather.com.cn/data/sk/101270104.htmlhttp://www.weather.com.cn/data/cityinfo/101270104.html http://m.weather.com.cn/data/101270104.htmlhttp://www.weather.com.cn/data/sk/101270104.html 这个网址的返回数据格式为:{"weatherinfo":{"city":"温江","cityid":"101270104","temp":"24","WD":"西南风","WS":"2级","SD":"77%","WSE":"2","time":"11:45","isRadar":"0","Radar":""}}写一段Python代码,保存文件名为DisplayWeatherInformation.py 实现将气象数据读取出来并打印出来:import requestsApiUrl = \ "http://www.weather.com.cn/data/sk/101270104.html"r = requests.get(ApiUrl)weatherinfo = r.jsonprint "City: " + weatherinfo["weatherinfo"]["city"]print "Temperature: " + weatherinfo["weatherinfo"]["temp"]print "Winds from the: " + weatherinfo["weatherinfo"]["WD"] + weatherinfo["weat$print "Humidity: " + weatherinfo["weatherinfo"]["SD"]print "Time: " + weatherinfo["weatherinfo"]["time"]运行 DisplayWeatherInformation.py 打印出本地当前的天气:root@raspberrypi:/home/pi# python DisplayWeatherInformation.py City: 温江Temperature: 26Winds from the: 南风2级Humidity: 69%Time: 15:45接下来你就可以使用抓取到的这些数据干一些事情了,例如通过天气数据,让树莓派自动播放穿衣的提醒。