此站点从该 API https://maps.pandora.net/api/getAsyncLocations 获取数据,查询参数中带有 search 值。结果是一个带有字段maplist 的 JSON 对象,其中包含 html 数据(单个 div)。这个 div 嵌入了几个以逗号分隔的 JSON 对象:
curl 'https://maps.pandora.net/api/getAsyncLocations?level=domain&template=domain&search=Melbourne+Victoria%2C+Australie'
所以我们需要将逗号分隔的 JSON 对象重新排列成一个数组来解析它。以下示例使用curl、jq(json 解析器)、sed 和pup(html 解析器)来提取数据:
search="Melbourne+Victoria+Australie"
curl -s -G 'https://maps.pandora.net/api/getAsyncLocations' \
-d 'level=domain' \
-d 'template=domain' \
-d "search=$search" | \
jq -r '.maplist' | \
pup -p div text{} | \
sed '$ s/.$//' | \
sed -e "\$a]" | \
sed '1s/^/[/' | \
jq '.[] | {
location: .location_name,
address: .address_1,
complement: (.city + "," + .big_region + " " + .location_post_code)
}'
在python 和python-requests 和beautifulsoup 中:
import requests
from bs4 import BeautifulSoup
import json
search = "Melbourne+Victoria+Australie"
response = requests.get(
'https://maps.pandora.net/api/getAsyncLocations',
params = {
'level':'domain',
'template':'domain',
'search': search
}
)
soup = BeautifulSoup(response.json()['maplist'], 'html.parser')
formatted_json = "[{}]".format(soup.div.string[:-1])
data = json.loads(formatted_json)
print([
(i['location_name'], i['address_1'], i['city'], i['big_region'], i['location_post_code'])
for i in data
])