首页 > 解决方案 > 网页抓取以从嵌入式 Google 地图链接中提取坐标

问题描述

import requests
import urllib2
from bs4 import BeautifulSoup
from pprint import pprint
import pandas as pd
import bs4

url = 'https://www.namus.gov/MissingPersons/Case#/53061'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html')
#print(soup.prettify())

findall = soup.find_all("a")

for link in findall:
    pprint(link.get("ng-href"))

当我运行代码时,我设置了一个元组而不是链接。我试过引用 href、src、ng-href 和非工作。当我真的需要谷歌地图的链接作为字符串时,我只能拉出 subSection。

#I get this: u'{{subSection.mapLink()}}'
#when I really need this: #"http://www.google.com/maps/place/35.9467011,-84.03260329999999"

我试图抓取的实际字符串如下所示:

<a ng-if="subSection.mapLink()" class="icon-text-link" ng-href="http://www.google.com/maps/place/35.9467011,-84.03260329999999" target="_blank" href="http://www.google.com/maps/place/35.9467011,-84.03260329999999">
                <i class="icon-location-pin"></i><span>Map</span>
            </a>

标签: pythongoogle-mapsweb-scrapingbeautifulsoupcoordinates

解决方案


由于这是一个有角度的网站,有很多信息是使用 Javascript 动态加载的,您可以检查网络选项卡以了解从哪里检索这些数据。在本例中,这是一个带有以下模板的 JSON API:

https://www.namus.gov/api/CaseSets/NamUs/MissingPersons/Cases/{CASE_ID}

它为您提供嵌入在页面中的所有信息,地图 url 可以动态构建,例如:

import requests

id = '53061'
resp = requests.get('https://www.namus.gov/api/CaseSets/NamUs/MissingPersons/Cases/{}'.format(id))
body = resp.json()

loc = body['sighting']['publicGeolocation']
coord = loc['coordinates']
print("address         : " + loc['formattedAddress'])
print("google map link : " + "http://www.google.com/maps/place/{},{}".format(coord['lat'],coord['lon']))

推荐阅读