import re import requests reponse = requests.get("https://www.natura2000.fr/carte-natura2000") regex = r"\"entity_id\":\"(\d+)\"" matches = re.findall(regex, reponse.text) kml_file = open("natura_2000.kml", "w", encoding="utf-8") kml_file.write(""" Natura 2000 """) for i, match in enumerate(matches): url = f"https://www.natura2000.fr/leaflet-ajax-popup/node/{match}/pop_up_n2000_field/und?_wrapper_format=drupal_ajax" response = requests.get(url) regex = r"href=\\u0022\\/site-natura\\/(.*?)\\u0022" match = re.search(regex, response.text) if not match: print(f"No match found for entity_id {match}.") continue site_url = f"https://www.natura2000.fr/site-natura/{match.group(1)}" response = requests.get(site_url) regex = r"(.*?) \| Natura 2000" match = re.search(regex, response.text) if not match: print(f"No name found for {site_url}.") continue name = match.group(1) regex = r"\"type\":\"(multipolygon|polygon)\"" match = re.search(regex, response.text) if not match: print(f"No geometry type found for {site_url}.") continue geometry_type = match.group(1) if geometry_type == "polygon": regex = r"\"points\":(\[\[.*?\]\])" elif geometry_type == "multipolygon": regex = r"\"points\":(\[\[\[.*?\]\]\])" else: print(f"Unsupported geometry type {geometry_type} for {site_url}.") continue match = re.search(regex, response.text) if not match: print(f"No coordinates found for {site_url}.") continue polygons = eval(match.group(1)) if geometry_type == "polygon": # Wrap single polygon in a list to treat it as multipolygon polygons = [polygons] kml_file.write(f""" {name} {name}
{site_url}
""") for polygon in polygons: kml_file.write(""" """) for point in polygon[0]: kml_file.write(f"{point['lon']},{point['lat']},0\n") kml_file.write(""" """) kml_file.write(f"""
""") print(f"Processed: {name} ({i+1: 5d}/{len(matches)})") kml_file.write("""
""")