1

How do I download files through Python using URLs located in a shapefile with ArcPy?

The script needs to read a shapefile, create folders and download images using URLs in more than 1 field/record (all starting with url*).

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Mar 30, 2021 at 0:46
0

1 Answer 1

2
import os
import arcpy
import shutil
import requests
# since I have no access to INDEX_utm20_PEI_Charlottetown_2008.shp, I am using 
# a test shapefile with 5 fields: 
# id (int), name (string), url1 (string), url2 (string), notes (string)
shapefile = r"data\photos.shp"
photo_location = r"data\photos"
fields = [field.name for field in arcpy.ListFields(shapefile, "url*", "string")]
with arcpy.da.SearchCursor(shapefile, ["id", "name"] + fields) as cursor:
 for row in cursor:
 
 id = row[0] # unique
 name = row[1]
 destination = os.path.join(photo_location, name)
 os.makedirs(destination, exist_ok=True)
 
 for url, field_name in zip(row[2:], fields):
 
 file_path = os.path.join(destination, f"{id}-{name}-{field_name}.jpg")
 
 response = requests.get(url, stream=True)
 if response.status_code == 200:
 with open(file_path, 'wb') as file:
 response.raw.decode_content = True
 shutil.copyfileobj(response.raw, file)

See also:


The above example does not use arcpy.env.workspace. I avoid using that whenever possible, especially in a a standalone script, or a complex script (using more than one path/workspace). I think this makes the script more explicit and easier to read.

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
answered Mar 30, 2021 at 0:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.