Reputation: 26406
I want to open a datauri in Python 3.6
It is described here: https://docs.python.org/3/library/urllib.request.html
But there's really no practical example of how to use it.
I've tried the following without luck. Can anyone suggest the right way to get the data from a datauri using urllib.request.DataHandler?
>>> req = urllib.request.Request("data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E")
>>> with urllib.request.DataHandler.data_open(req) as response:
... data = response.read()
File "<stdin>", line 2
data = response.read()
^
IndentationError: expected an indented block
>>> data = response.read()
File "<stdin>", line 1
data = response.read()
^
IndentationError: unexpected indent
>>> with urllib.request.DataHandler.data_open(req) as response:
... data = response.read()
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: data_open() missing 1 required positional argument: 'req'
>>> with urllib.request.DataHandler.data_open(req) as response:
... data = response.read()
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: data_open() missing 1 required positional argument: 'req'
>>>
Upvotes: 1
Views: 1509
Reputation: 414695
You could pass data URI to urlopen()
:
#!/usr/bin/env python3
from urllib.request import urlopen
url = "data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E"
with urlopen(url) as response:
data = response.read()
print(data.decode())
Upvotes: 3