Newbie problem with urllib.request.urlopen
Peter Otten
__peter__ at web.de
Tue Sep 26 13:03:10 EDT 2017
Bernie Connors wrote:
> On Tuesday, September 26, 2017 at 12:32:18 PM UTC-3, Bernie Connors wrote:
>> Hello,
>>
>> My first post here on C.L.P. I have only written a few python
>> scripts in 2.7 and now I'm trying my first python 3 script. Can
>> you tell me why this snippet won't run?
>> -----------------------
>> from urllib.request import urlopen
>>
>> with
>>
urlopen('http://geonb.snb.ca/arcgis/rest/services/GeoNB_SNB_Parcels/MapServer/0/query?outSR=4617&f=JSON&where=PID='75385120'')
>> as conn:
>> print(conn)
>> -----------------------
>> Thanks,
>> Bernie.
>
> Thomas,
>
> The PID parameter at the end of my url must be enclosed in single
> quotes, '75385120', or the API won't execute the query. I have the
Then use " to quote the Python string:
>>> import urllib.request
>>> url =
"http://geonb.snb.ca/arcgis/rest/services/GeoNB_SNB_Parcels/MapServer/0/query?outSR=4617&f=JSON&where=PID='75385120'"
>>> with urllib.request.urlopen(url) as conn:
... print(conn)
... data = conn.read()
...
<http.client.HTTPResponse object at 0x7fe844448390>
>>> data[:20]
b'{"displayFieldName":'
Looks good. To convert the data into a Python dict:
>>> import json
>>> d = json.loads(data.decode("utf-8"))
>>> d
{'features': [{'attributes': {'PID': '75385120'}, 'geometry': {'rings':
[snip]
PS: For other ways to write a Python string literal have a look into the
tutorial:
https://docs.python.org/3.6/tutorial/introduction.html#strings
More information about the Python-list
mailing list