我知道之前有人問過這個問題,但我找不到任何在 Google colab 中完成的實體(而不是在本地)。我正在嘗試使用請求和 BeautifulSoup 從 API 輸出中抓取區域名稱和相關的緯度和經度。我的代碼如下:
#Importing tools
import numpy as np
import pandas as pd
import requests
import string
from bs4 import BeautifulSoup
import os
#Getting the HTML elements from the URL
URL = "http://api.positionstack.com/v1/forward?access_key=4d197793636f1badcdc02c14da0f8da0&query=London&limit=1"
html = requests.get(URL)
soup = BeautifulSoup(html.content, 'html.parser')
#I went onto the website, inspected it and found that the latitudes, longitudes and place names are in the span.n elements
#I'm grabbing this from the website here and viewing it
soup_k = soup.find_all("span", class_="n")
soup_k
但它只是輸出:
[]
我還嘗試了使用檢查可以找到的所有其他元素,但它們都沒有回傳任何內容。我看到類似問題的解決方案表明這些元素隱藏在 Javascript 后面,但我認為情況并非如此......
任何關于它為什么回傳空串列或幫助抓取此頁面的想法將不勝感激!謝謝
免責宣告:我是編碼新手,我試圖確保我的術語是正確的,并且以正確的方式提出問題,但我仍在學習 - 任何指向正確方向的指標總是受歡迎的
uj5u.com熱心網友回復:
它不是一個網站,它是一個回應jsonnot的 api html。所以BeautifulSoup不需要,只需抓住json并選擇你的屬性:
import requests
URL = "http://api.positionstack.com/v1/forward?access_key=4d197793636f1badcdc02c14da0f8da0&query=London&limit=1"
res = requests.get(URL).json()
資源輸出:
{'data': [{'latitude': 51.509648, 'longitude': -0.099076, 'type': 'locality', 'name': 'London', 'number': None, 'postal_code': None, 'street': None, 'confidence': 1, 'region': 'Greater London', 'region_code': None, 'county': None, 'locality': 'London', 'administrative_area': None, 'neighbourhood': None, 'country': 'United Kingdom', 'country_code': 'GBR', 'continent': 'Europe', 'label': 'London, England, United Kingdom'}]}
要訪問您的屬性:
lat = res['data'][0]['latitude']
lng = res['data'][0]['longitude']
region = res['data'][0]['region']
print(lat,lng,region)
輸出:
51.509648 -0.099076 Greater London
uj5u.com熱心網友回復:
我也遇到過這種情況。如果將 BS 物件列印為字串,則可以看到每個 HTML 元素之間都有段落符號。BS 將這些段落符號識別為元素并將它們決議為空元素。因此,您將檢索空元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407891.html
標籤:
