在Spark体验开始前需要准备环境和数据,环境的准备可以自己按照Spark官方文档安装。笔者选择使用CDH集群安装,可以参考笔者之前的文章:Cloudera Manager大数据集群环境搭建
至于数据的准备就是本文的主要内容,数据采用python爬虫的方式,爬去上一个月上海的天气数据,参考了https://www.cnblogs.com/haha-point/p/7467221.html,但是因为网站做了反爬虫,研究了一下,发下只要加上header请求就可以规避掉反爬问题。
上海市19年2月的天气可以通过http://lishi.tianqi.com/shanghai/201902.html获取
#encoding:utf-8
import requests
from bs4 import BeautifulSoup
url = "http://lishi.tianqi.com/shanghai/201902.html"
if __name__ == '__main__':
target_file = open("weather.txt",'w')
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8',
'Cache-Control':'no-cache',
'Cookie':'cityPy=shanghai; UM_distinctid=1696d7851820-0518fd894ef605-36657905-1aeaa0-1696d7851832da; CNZZDATA1275796416=2105206279-1552318077-https%253A%252F%252Fwww.cnblogs.com%252F%7C1552318077; Hm_lvt_ab6a683aa97a52202eab5b3a9042a8d2=1552319796,1552319840,1552319867; Hm_lpvt_ab6a683aa97a52202eab5b3a9042a8d2=1552322278'
}
response = requests.get(url,headers=headers)
soap = BeautifulSoup(response.text, 'html.parser')
weather_list = soap.select('div[class="tqtongji2"]')
for weather in weather_list:
weather_date = weather.select('a')[0].string.encode('utf-8')
ul_list = weather.select('ul')
i = 0
for ul in ul_list:
li_list = ul.select('li')
str = ""
for li in li_list:
str += li.string.encode('utf-8') + ','
if i != 0:
target_file.write(str + '\n')
i += 1
target_file.close()
通过以上代码,把19年2月的天气存到了weather.txt文件中,数据以逗号方式分割
数据准备好了之后,下一篇是Spark基本API的体验