python爬虫+数据可视化项目(一)
爬取目标:中国天气网(起始url:http://www.weather.com.cn/textFC/hb.shtml#)
爬取内容:全国实时温度最低的十个城市气温排行榜
使用工具:requests库实现发送请求、获取响应。
beautifulsoup实现数据解析、提取和清洗
pyechart模块实现数据可视化
爬取结果:柱状图可视化展示:
![](https://img2018.cnblogs.com/blog/1553680/201812/1553680-20181220210324207-578505491.png)
直接放代码(详细说明在注释里,欢迎同行相互交流、学习~):
1 import requests
2 from bs4 import BeautifulSoup
3 from pyecharts import Bar
4
5 ALL_DATA = []
6 def send_parse_urls(start_urls):
7 headers = {
8 "User-Agent": "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)"
9 }
10 for start_url in start_urls:
11 response = requests.get(start_url,headers=headers)
12 # 编码问题的解决
13 response = response.text.encode("raw_unicode_escape").decode("utf-8")
14 soup = BeautifulSoup(response,"html5lib") #lxml解析器:性能比较好,html5lib:适合页面结构比较混乱的
15 div_tatall = soup.find("div",class_="conMidtab") #find() 找符合要求的第一个元素
16 tables = div_tatall.find_all("table") #find_all() 找到符合要求的所有元素的列表
17 for table in tables:
18 trs = table.find_all("tr")
19 info_trs = trs[2:]
20 for index,info_tr in enumerate(info_trs): # 枚举函数,可以获得索引
21 # print(index,info_tr)
22 # print("="*30)
23 city_td = info_tr.find_all("td")[0]
24 temp_td = info_tr.find_all("td")[6]
25 # if的判断的index的特殊情况应该在一般情况的后面,把之前的数据覆盖
26 if index==0:
27 city_td = info_tr.find_all("td")[1]
28 temp_td = info_tr.find_all("td")[7]
29 city=list(city_td.stripped_strings)[0]
30 temp=list(temp_td.stripped_strings)[0]
31 ALL_DATA.append({"city":city,"temp":temp})
32 return ALL_DATA
33
34 def get_start_urls():
35 start_urls = [
36 "http://www.weather.com.cn/textFC/hb.shtml",
37 "http://www.weather.com.cn/textFC/db.shtml",
38 "http://www.weather.com.cn/textFC/hd.shtml",
39 "http://www.weather.com.cn/textFC/hz.shtml",
40 "http://www.weather.com.cn/textFC/hn.shtml",
41 "http://www.weather.com.cn/textFC/xb.shtml",
42 "http://www.weather.com.cn/textFC/xn.shtml",
43 "http://www.weather.com.cn/textFC/gat.shtml",
44 ]
45 return start_urls
46
47 def main():
48 """
49 主程序逻辑
50 展示全国实时温度最低的十个城市气温排行榜的柱状图
51 """
52 # 1 获取所有起始url
53 start_urls = get_start_urls()
54 # 2 发送请求获取响应、解析页面
55 data = send_parse_urls(start_urls)
56 # print(data)
57 # 4 数据可视化
58 #1排序
59 data.sort(key=lambda data:int(data["temp"]))
60 #2切片,选择出温度最低的十个城市和温度值
61 show_data = data[:10]
62 #3分出城市和温度
63 city = list(map(lambda data:data["city"],show_data))
64 temp = list(map(lambda data:int(data["temp"]),show_data))
65 #4创建柱状图、生成目标图
66 chart = Bar("中国最低气温排行榜") #需要安装pyechart模块
67 chart.add("",city,temp)
68 chart.render("tempture.html")
69
70 if __name__ == '__main__':
71 main()
请关注,未完待续!