如下所示:1.pipinstallrequests2.pipinstalllxml3.pipinstallxlsxwriterimportrequests#想要爬必须引fromlxmlimport
如下所示:
1.pip install requests
2.pip install lxml
3.pip install xlsxwriter
import requests #想要爬必须引
from lxml import html #这个是用于页面爬取
import xlsxwriter#操作Excel表格库
workbook = xlsxwriter.Workbook('E:/test/test.xlsx')# 新建的Excel表格文档路径
worksheet = workbook.add_worksheet() # 建立sheet, 可以work.add_worksheet('employee')来指定sheet名,但中文名会报UnicodeDecodeErro的错误
i = 1;# 作用于Excel表格第几行数与接口第几页
#写一个死循环让他一直爬取数据
while (True):
import json# 这里这么引入json是因为不这么引入当循环到第二次就会报没有引入json的错,所以循环引入了
#接口str(i)表示第几页一定要转为字符串格式,要不会报不是字符串的错
url = "https://www.amap.com/service/poiInfo?query_type=TQUERY&pagesize=20&pagenum="+str(i)+"&qii=true&cluster_state=5&need_utd=true&utd_sceneid=1000&div=PC1000&addr_poi_merge=true&is_classify=true&zoom=14.81&city=110000&geoobj=115.7|39.4|117.4|41.6&keywords=水果店"
# 将cookies字符串组装为字典
cookies_str = "guid=f86f-79f2-5b0b-69a3; UM_distinctid=16386a114ca143-07312d6ae4d5af8-47534130-1fa400-16386a114ccb85; CNZZDATA1255626299=1778515027-1526967763-https%253A%252F%252Fwww.baidu.com%252F%7C1527219534; cna=5hWHEx7lRkECAXL4l+2LMAfU; isg=BGBg3rAqL6QOz5OkNN5wbxWiMm7ywUxc_zvQMtpxLHsO1QD_gnkUwzbHaf3V_vwL; _uab_collina=152697209566826431413694; key=bfe31f4e0fb231d29e1d3ce951e2c780"
cookies_dict = {}
for cookie in cookies_str.split(";"):
k, v = cookie.split("=", 1)
cookies_dict[k.strip()] = v.strip()
pass
# 其他请求头参数
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0'
}
# 让服务器认为你是通过浏览器访问页面
page = requests.get(url=url,cookies=cookies_dict,headers=headers);
# 转json
json = json.loads(page.text);
# 判断这个字段如果为未找到相关信息则跳出死循环
if json['data']['lqii']['change_query_tip'] == '未找到"水果店"相关结果':
break;
pass
# 获取json长度用于添加Excel第几行
length = len(json['data']['poi_list']);
# 循环json数据向Excel表格添加
for index,j in enumerate(json['data']['poi_list']):
worksheet.write(index+(i-1)*length,0,j['disp_name'])
worksheet.write(index+(i-1)*length,1,j['tel'])
worksheet.write(index+(i-1)*length,2,j['address'])
pass
i+=1
pass
workbook.close()#最后关闭Excel表格 注意事项,当Excel表格正在打开的情况下会报没有关闭的错所以请关闭Excel再运行此程序
以上这篇python requests爬取高德地图数据的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
python requests 高德地图