*本文仅就相关技术细节进行学术交流,请勿用作他途*

如何获取网页中发布的位置信息,在地图上进行标记可视化?

  • Step 1: 数据获取
  • Step2: 地址解析
  • Step3: 地图可视化

地址编码后的数据导入tableau得到的地图如下(可放大):


Step 1: 数据爬取

我们采用requests进行网页爬取,利用BeautifulSoup和re进行整理和信息抽取。代码如下:

#libraries
from bs4 import BeautifulSoup
import requests
import re
import pandas as pd
import time# define a function of crawing html
def geturl(url):r = requests.get(url)r.encoding = r.apparent_encodingreturn r.text# data crawing from the public notice
url = 'https://mp.weixin.qq.com/s/MkKsQkgvUWbwj8z9jG_Zng'
text = geturl(url) #get info from original link
file = open("shanghai0404.txt",'w') #save as a new file
file.write(text) #write info# parsing
soup = BeautifulSoup(text, "html.parser")
info = soup.find('div', 'rich_media_content')
x = str(info)# get the infection data as a list
addresses = re.findall('</span></p><p>.*?<span style="font-size: 16px;">([^已<2022].+?)?[,。、<]+?', x)
file = open("shanghai0404_addresses.txt",'w') #save as a new file
for i in addresses:file.write(i+'\r') #write info# get the summary data of all districts
districts = re.findall('2022年4月4日,(.+?区)[无]?新增([\d]+?)?.*?确诊病例,新增([\d]+?)例.*?无症状感染者',x)
li = []
for item in districts:di = []di.extend(item)li.append(di)df = pd.DataFrame(li,columns=['districts','positive','asymptomatic'])
df.to_csv('shanghai2022_04_04_districts.csv')print(addresses)
print(districts)
print(df)

这一步可得到两个txt文档,分别记录网页源代码、爬取到的街道信息。

其中最重要的是爬取到的地址信息,一共3000+,部分items如下:

'八灶村郭家宅', '八灶村周家宅', '白杨路1065弄', '板泉路1201弄', '板泉路2000弄', '板泉路2101弄', '板泉路25号', '北艾路1077弄', '北艾路1200弄', '北艾路1500弄', '北艾路155弄', '北艾路1660弄', '北艾路1765弄', '北蔡大街31弄', '北新园路460弄', '北洋泾路601号', '北园路258弄', '北张家浜路68号', '北中路175弄', '北中路280弄', '北中路480弄', '北庄村', '碧云路1198号', '碧云路86弄', '博成路周家渡路交界口工地生活区‘......

执行上一段代码保存的txt中存取了这部分信息。


Step2:地理编码

有了上面的地址信息,要想在地图中展现出来还需要有经纬度信息才行。这里就需要进行地址解析。用到的是google官方的geocoding api,免费,但是有一定限制,由于我们要发送3000+请求信息,需要设置time.sleep(),避免请求过于频繁导致失败。

这部分的逻辑可参考我的上一篇文章:

地址解析:使用Google API将地址文本转换为经纬度_Liagogo的博客-CSDN博客本文将提供Geocoding API的基础使用指南,包括:设置谷歌云平台账号及项目、基础地址请求代码、返回值解析及信息提取https://blog.csdn.net/liatan/article/details/123973890?spm=1001.2014.3001.5502

(*必须在谷歌云平台申请并替换自己的key,否则无法运行)

也可以用其它API或者直接用geocoder 等现成的包,下面只是就Google API提供一个参考。

具体code如下(需要一点时间才能run完):

#libraries
from bs4 import BeautifulSoup
import requests
import re
import pandas as pd
import urllib
import json
import time# define a function of crawing json from google api
def geturl(url):r = requests.get(url)r.encoding = r.apparent_encodingreturn r.text# define a function of parsing json from google api
def getinfo(js):i = []js = json.loads(text)i.append(js['results'][0]['formatted_address'])i.append(js['results'][0]['geometry']['location']['lat'])i.append(js['results'][0]['geometry']['location']['lng'])return(i)key = 'ENTER YOUR KEY HERE'# replace with your own key copied from google cloud platformaddresses = open("shanghai0404_addresses.txt",'r').readlines()
print(addresses[0].strip())data = []
for location in addresses:ls = []addr = '上海市'+location.strip()url = 'https://maps.googleapis.com/maps/api/geocode/json?{}&key={}'.format(urllib.parse.urlencode({'address':addr}), key)try:text = geturl(url)except:time.sleep(7)try:text = geturl(url)except:text = ''try:js = json.loads(text)except:js = Noneif js == None or 'status' not in js or js['status'] != 'OK':z = ['','','']z.append(addr)data.append(z)continueelse:z = getinfo(js)z.append(addr)data.append(z)df = pd.DataFrame(data,columns=['f_location','latitude','longitude','location'])
df.to_csv('shanghai2022_04_04.csv')

最后得到的就是包括地址、经纬度信息的csv,下一步就可以准备画图啦。


Step 3: 地图可视化

首先,要在地图上可视化,我们需要上海市的shp地图文件,这个免费的资源还不是很好找,file放在github里了,可自取:https://github.com/Liagogo/Shanghai_covid_2022springhttps://github.com/Liagogo/Shanghai_covid_2022spring后续标记的逻辑是,将dataframe转换为geodataframe,将经纬度转化为points,然后就可以被识别并在上面的地图里标记。具体code很简单:

from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeTypeimport pandas as pd
import matplotlib.pyplot as plt
import descartes
import geopandas as gpd
from shapely.geometry import Point, Polygon
%matplotlib inline# -------------------------------------
# visualize the infectors locations data# first, import the .shp of Shanghai
# import the map
shanghai_map = gpd.read_file('./stanford-dv960kb3448-shapefile/shanghai1.shp')
# plot the empty map
fig,ax = plt.subplots(figsize = (15,15))
shanghai_map.plot(ax = ax, color = 'grey')# read the data
df = pd.read_csv('shanghai2022_04_04.csv')
crs = {'init': 'epsg:4326'}
# creat points to be shown
geo = [Point(xy) for xy in zip(df['longitude'], df['latitude'])]
# gen geodataframe
geo_df = gpd.GeoDataFrame(df, crs=crs, geometry=geo)
fig,ax = plt.subplots(figsize = (15,15))# mark on the map
shanghai_map.plot(ax = ax, color = 'lightgray')
geo_df.plot(ax = ax, markersize = 60, color = 'darkred', alpha = 0.2, marker = 'o')

可从以下链接直接下载所有代码及数据、地图文档:

GitHub - Liagogo/Geocoding-and-Visualizing-covid-cases-Shanghai-2022spring: Data crawling, geocoding and visualization of the covid cases in the new infecting wave in Shanghai on April 2022 with the official public dataData crawling, geocoding and visualization of the covid cases in the new infecting wave in Shanghai on April 2022 with the official public data - GitHub - Liagogo/Geocoding-and-Visualizing-covid-cases-Shanghai-2022spring: Data crawling, geocoding and visualization of the covid cases in the new infecting wave in Shanghai on April 2022 with the official public datahttps://github.com/Liagogo/Geocoding-and-Visualizing-covid-cases-Shanghai-2022spring

欢迎下载尝试优化~

微信公众号同步内容:

Python绘制上海疫情风险地图|数据爬取+地址解析+可视化如何获取上海发布公布的位置信息,在地图上进行标记可视化?https://mp.weixin.qq.com/s?__biz=MzA4OTg4Nzg4Nw==&mid=2247483784&idx=1&sn=5aada7539eeaa1e24add8b3bdc994bb9&chksm=90154468a762cd7e7a3c64371e65295fad56886568ea7e140db36eb423153b9f74896cfe2015&token=501224681&lang=zh_CN#rd

如何用python可视化疫情风险区?地图标记位置信息:数据爬取+地址解析+可视化相关推荐

  1. 基于python的自媒体和官媒数据爬取、可视化分析及云词图制作

    创作不易,如果以下内容对你有帮助,别忘了点一个赞,让更多的小伙伴能看到吧~~ 1. 问题描述 为了研究自媒体和官媒的传播新闻<武汉快递小哥汪勇的先进事迹>的及时性和传播力度,对比两种传播途 ...

  2. python数据分析图表展示_NBA数据分析_python数据爬取_可视化图形_python数据可视化案例-帆软...

    之前手痒做了一次NBA可视化分析,发个微头条,好多人追着我问教程,这两天终于闲下来了,花时间整理这篇NBA可视化分析教程,手把手教大家做一次炫酷的数据可视化分析! 先部分展示本次教程的作品: 数据获取 ...

  3. 赶集网住房信息数据爬取与可视化

    爬虫–scrapy 根据赶集网租房查询不同户型的价格信息,统计不同户型的最高价,最低价,均价,绘制不同户型均价折线图.柱状图 搭建环境 建议换成国内镜像 豆瓣 https://pypi.douban. ...

  4. 疫情数据爬取,可视化及其预测

    疫情数据爬取及可视化 数据爬取及保存(provinceDataGet.py) import requests import json import pandas as pd# 地区 areas = [ ...

  5. python爬取微博热搜显示到折线图_微博热搜榜前20信息数据爬取进行数据分析与可视化...

    一.设计方案 1.主题式网络爬虫名称:微博热搜榜前20信息数据爬取进行数据分析与可视化 2.爬取内容与数据特征分析:爬取微博热搜榜前20热搜事件.排名与热度,数据呈一定规律排序. 3.设计方案概述:思 ...

  6. 【爬虫+数据可视化毕业设计:英雄联盟数据爬取及可视化分析,python爬虫可视化/数据分析/大数据/大数据屏/数据挖掘/数据爬取,程序开发-哔哩哔哩】

    [爬虫+数据可视化毕业设计:英雄联盟数据爬取及可视化分析,python爬虫可视化/数据分析/大数据/大数据屏/数据挖掘/数据爬取,程序开发-哔哩哔哩] https://b23.tv/TIoy6hj

  7. 基于python大数据爬取房价数据可视化

    基于python大数据爬取房价数据可视化

  8. Python 大数据分析疫情:如何实现实时数据爬取及 Matplotlib 可视化?

    作者 | 杨秀璋 来源 | CSDN博客专家Eastmount 责编 | 夕颜 思来想去,虽然很忙,但还是挤时间针对这次肺炎疫情写个Python大数据分析系列博客,包括网络爬虫.可视化分析.GIS地图 ...

  9. educoder python入门之基础语法-用python实现豆瓣短评通用爬虫(登录、爬取、可视化分析)...

    原创技术公众号:bigsai 前言 在本人上的一门课中,老师对每个小组有个任务要求,介绍和完成一个小模块.工具知识的使用.然而我所在的组刚好遇到的是python爬虫的小课题. 心想这不是很简单嘛,搞啥 ...

最新文章

  1. e.printStackTrace()导致的锁死
  2. 自考计算机和行政管理哪个好考,自考行政管理好考吗?自考行政管理都考哪些科目?...
  3. T-SQL DISTINCT
  4. 超详细的CentOS7中安装Git,yum安装和自己编译安装
  5. JVM 学习笔记 1. JVM 运行模型
  6. 【独家】去哪儿网PRD兵法秘籍大公开,火爆课程精彩直击!
  7. MQTT--物联网(IoT)消息推送协议
  8. [转]python 中的字符串连接
  9. 啥是Attention?
  10. Flask源码解析:从第一个版本开始阅读Flask源码
  11. 【转】重装系统后找不到硬盘
  12. vb6启动时提示安装VS2008 SP1
  13. react 路径跳转组件不跳转_Taro 小程序开发大型实战(二):多页面跳转和 Taro UI 组件库...
  14. mysql ON DUPLICATE KEY UPDATE重复插入时更新
  15. mac下加速下载百度云资源
  16. Ubuntu20.04 图片标注工具labelImg
  17. 网址导航7654推广
  18. Android 关于佳博和汉印蓝牙热敏打印机开发
  19. 使用Arduino Motor Shield控制步进制电机
  20. Python项目通用的目录结构总结

热门文章

  1. linux rtl8723bu 蓝牙,RTL8723BU(wifi Bluetooth) 移植
  2. Linux/Unix-stty命令详解
  3. [MATLAB] 图像的插值算法1:MATLAB中的插值函数及其原理
  4. 如何制作和发布网页(上)
  5. iOS-Core-Animation-Advanced-Techniques(一)
  6. mysql数据库自动生成数据库开发设计文档
  7. 海康摄像头二次开发详解,包含海康摄像头登录、海康云台控制、视频下载等功能
  8. java speech sdk_Microsoft Speech SDK开发包 使用
  9. Python通过MQTT协议上传物联网数据给ThingsBoard
  10. 雅虎微软合作对手机搜索领域的影响