I need to retrieve the WMS version from a QGIS layer in Python. I can see the version in amongst the metadata()
, but is there a better way than having to parse all of that HTML for one little value?
1 Answer
Bit of a hacky way but you can avoid using BeautifulSoup by splitting the metadata (which is printed as a looong string) at "WMS Version"
and print off the next few characters which represents the version:
layer = iface.activeLayer()
string = "<tr><td>WMS Version</td><td>"
layer.metadata().split(string)[1][:5]
Which for my WMS layer prints:
u'1.3.0'
Edit:
If you want to isolate it more accurately by extracting only the version number <td>version_number</td>
then I would suggest using regular expressions:
import re
layer = iface.activeLayer()
string = "<tr><td>WMS Version</td><td>(.+?)</td>"
result = re.search(string, layer.metadata())
if result:
wms_version = result.group(1)
print wms_version
Second edit:
As @Tom Chadwin found out to his problem in regards to translating the WMS version from another language, replacing "WMS Version"
with QCoreApplication.translate("QgsWmsProvider", "WMS Version")
seems to have worked. So the edited code would be:
import re
layer = iface.activeLayer()
string = "<tr><td>" + QCoreApplication.translate("QgsWmsProvider", "WMS Version") + "</td><td>(.+?)</td>"
result = re.search(string, layer.metadata())
if result:
wms_version = result.group(1)
print wms_version
-
Can we guarantee that the version string will always be 5 characters long? I suppose a second
split()
on the following tag would isolate it more reliably. Would it be.split('</td>')[0]
? Commented Oct 15, 2016 at 23:37 -
@TomChadwin - You're probably right in that we can't guarantee if the string will be 5 characters so I've edited my post to provide an alternative method which should extract everything inside the
<td>version_number</td>
tags =)– JosephCommented Oct 17, 2016 at 9:34 -
1Thanks for the fully worked example - much appreciated. It's not what I wanted to do, but since no alternative has been suggested, I've accepted your answer. Thanks! Commented Oct 17, 2016 at 11:59
-
@TomChadwin - Most welcome, it does seem like a hassle to obtain a simple version number but hopefully there is a method to extract it directly instead of through the metadata ;)– JosephCommented Oct 17, 2016 at 12:00
-
1OK, it looks as though
QCoreApplication.translate("QgsWmsProvider", "WMS Version")
does the trick. Replace "WMS Version" in your code with the above. Commented Feb 2, 2017 at 14:24
WMT_MS_Capabilities/@version
if you get no response it's a version 1.3.0 service...metadata()
is the result of GetCapabilites in HTML format and you can also use BeautifulSoup