6

I'm trying to access data from a WFS-server, E.g. https://geo.barentswatch.no/geoserver/bw/ows?

I manage to import single layers by:

uri = "https://geo.barentswatch.no/geoserver/bw/ows?srsname=EPSG:4326&typename=bw:npdsurveyongoing_latest&version=1.0.0&request=vlayer=QgsVectorLayer"
vlayer = QgsVectorLayer(uri, "bw:npdsurveyongoing_latest", "WFS")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

However, I want to import all available layers and would like them to automatically to be named by their original typeName. Seems a bit unnecessary to hardcode all names in beforehand accessing the server, but I have been struggling to figure out the codes for this.

Any way to do this in pyqgis?

6

Not the cleanest of solutions but you could use a combination of urllib2 to read your XML file and regular expressions to extract the names.

So we can:

  • Loop through each line in the XML file
  • Extract the names of the layers
  • Insert the names into the same uri you provided
  • Then add it to QGIS

This is the code I used:

import urllib2, re

file = urllib2.urlopen('https://geo.barentswatch.no/geoserver/ows?service=wfs&version=1.0.0&request=GetCapabilities')
data = file.read()
string = '<FeatureType><Name>(.+?)</Name><Title>'
for word in data.split():
    layer = re.search(string, word)
    if layer is not None:
        uri = "https://geo.barentswatch.no/geoserver/bw/ows?srsname=EPSG:4326&typename={name}&version=1.0.0&request=vlayer=QgsVectorLayer".format(name = layer.group(1))
        vlayer = QgsVectorLayer(uri, layer.group(1), "WFS")
        QgsMapLayerRegistry.instance().addMapLayer(vlayer)

file.close()

Result:

Result

1
  • @Sigurd - Most welcome! Glad it worked :) – Joseph Apr 5 '17 at 8:59
3

For others new to WFS in python, I also fount OWSLib to be quite helpful, ref.: https://geopython.github.io/OWSLib/

An easy approach to list all layers (which could be looped through for import in QGIS):

from owslib.wfs import WebFeatureService
wfs = WebFeatureService(url='https://geo.barentswatch.no/geoserver/ows?', version='1.0.0')
list(wfs.contents)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.