3

How can I get total featurecount from a WFS service? I need to download all features, 1000 at a time, so I want to know when to stop (Or can I just keep going until the response is empty?)

I've tried to find something here, but I dont:

https://slwgeo.artdata.slu.se/geoserver/wfs?request=GetCapabilities

The service name is: SLW:AllSwedishOccurrences

This is the code I'm using which is working but I need to know when to stop.

import os
from owslib.wfs import WebFeatureService


downloadto = '/home/bera/GIS/csvfiler_paging/'

wfs1 = WebFeatureService(url=r'https://slwgeo.artdata.slu.se/geoserver/wfs?', version='1.1.0')
wfs1.timeout=120

for i in range(0,10000,1000): #I need ot replace 10000 with the total feature count
    print(i)
    response = wfs1.getfeature(typename='SLW:AllSwedishOccurrences', maxfeatures=1000, outputFormat='csv', startindex=i)
    outfile=os.path.join(downloadto,'data_{0}.csv'.format(str(i)))
    out=open(outfile, 'wb')
    out.write(response.read())
    out.close()
0
4

I never found how to do it in Python with owslib.wfs, therefore i use the GetFeature request of WFS v.1.1.0 with parameter resulttype=hits (as in Only return the NumberOfFeatures in a WFS query) and the Python library requests

From WFS GetFeature request blank XML for some FeatureTypes

the value hits indicates that a web feature service should process the GetFeature request and rather than return the entire result set, it should simply indicate the number of feature instance of the requested feature type(s) that satisfy the request.

import requests
wfs_url = 'https://slwgeo.artdata.slu.se/geoserver/wfs'
layer = 'SLW:AllSwedishOccurrences'
r = requests.get(wfs_url, params={
     'service': 'WFS',
     'version': '1.1',
     'request': 'GetFeature',
     'resultType': 'hits',
     'typename': layer
 })

print(r.content)

b'<?xml version="1.0" encoding="UTF-8"?><wfs:FeatureCollection xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" numberOfFeatures="25000" timeStamp="2021-08-29T12:28:39.355Z" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"/>'

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(r.content)
print(myxml.attrib)
{'numberOfFeatures': '25000', 'timeStamp': '2021-08-29T12:28:39.355Z', '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': 'http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd'}
print(myxml.attrib['numberOfFeatures'])
25000

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.