且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python编程:通过百度地图接口抓取机构的地址和电话信息

更新时间:2022-09-05 10:26:25

基本原理

1、百度地图开放了搜索接口

http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi

2、使用【地点检索】接口搜索商家的地址、电话等信息

3、基本使用流程

(1) 申请百度账号

(2) 申请成为百度开发者

(3) 获取服务密钥(ak)

(4) 发送请求,使用服务

代码示例

import requests


def baidu_map_search(key):
    # 注册->新建应用 http://lbsyun.baidu.com/
    apk_key = "xxxxxxxxxxxx"

    url = "http://api.map.baidu.com/place/v2/search"

    params = {
        "query": key,
        "output": "json",
        "ak": apk_key,
        "region": "北京",
        "page_size": 20,
        "page_num": 1,
        "scope": 2
    }

    response = requests.get(url, params)
    result = response.json()
    status = result.get("status")
    message = result.get("message")

    if status != 0 and status != 2:
        raise Exception(message)

    data = result.get("results", {})
    for row in data:
        item = {
            "name": row.get("name", ""),
            "address": row.get("address", ""),
            "province": row.get("province", ""),
            "city": row.get("city", ""),
            "area": row.get("area", ""),
            "telephone": row.get("telephone", ""),
            "tag": row.get("detail_info", {}).get("tag", ""),
        }

        for k, v in item.items():
            print("{}: {}".format(k, v))


if __name__ == '__main__':
    baidu_map_search("学校")

抓取结果

name: 中间民族大学
address: 北京市海淀区中关村南大街27号
province: 北京市
city: 北京市
area: 海淀区
telephone: (010)68933971
tag: 教育培训;高等院校

name: 北京科技大学
address: 北京市海淀区学院路30号
province: 北京市
city: 北京市
area: 海淀区
telephone: (010)62332312
tag: 教育培训;高等院校
...