JayJay
JayJay

Reputation: 203

How to get coordinates from a Wikipedia page using Python?

I want to get the coordinates of a given Wikipedia page. I tried to use the Wikipedia API, however the only relevant method is the geosearch() that returns a page given a pair of coordinates and i want the exact opposite.

Upvotes: 2

Views: 1055

Answers (3)

required_banana
required_banana

Reputation: 9

Use the wikipedia library. If you don't have it, use pip install wikipedia. Great. Now for the coordinates. Let's say you want to find the coordinates of Beijing, China. (You need to specify the country.)

import wikipedia as wiki
page = wiki.page("China")
coordinates = page.coordinates
print(coordinates)

This will output: (Decimal('39.90666666999999989684511092491447925567626953125'), Decimal('116.3974999999999937472239253111183643341064453125')). See! That simple. No API. I assure you, if you go to PyPI and search "wikipedia", you will find the wikipedia package.

Upvotes: 1

AXO
AXO

Reputation: 9096

You've not mentioned which Python library you're using but in general, e.g. for getting the coordinates of the Washington, D.C. article using the Geosearch API one may use the following URL:

https://en.wikipedia.org/w/api.php?action=query&prop=coordinates&titles=Washington,%20D.C.&%20format=json

Upvotes: 2

Matthew Gaiser
Matthew Gaiser

Reputation: 4783

Not sure about doing it with the Wikipedia API, but it can easily be done separately.

import requests
from bs4 import BeautifulSoup as bs
req = requests.get("https://en.wikipedia.org/wiki/Calgary").text
soup = bs(req, 'lxml')
latitude = soup.find("span", {"class": "latitude"})
longitude = soup.find("span", {"class": "longitude"})
print(latitude.text, longitude.text)

Upvotes: 2

Related Questions