Here are three possible solutions. The first uses the native Python urllib.request.urlopen function. The second one uses the third-party library lxml. The second one uses the HTMLParser class from the native html.parser module. The second and third ones use a third-party library for parsing data URLs called python-datauri
html_string = """
<a href="data:text/csv;charset=UTF-8,%22csvcontentfollows">
<a href="data:text/csv;charset=UTF-8,%22csvcontentfollows">
<a href="data:text/csv;charset=UTF-8,%22csvcontentfollows">
"""
from contextlib import ExitStack
from urllib.request import urlopen
import lxml.etree
HREF = "href"
tree = lxml.etree.fromstring(html_string, lxml.etree.HTMLParser())
uris = (
item.attrib[HREF]
for item in tree.iterdescendants()
if HREF in item.attrib
)
with ExitStack() as stack:
resources = (stack.enter_context(urlopen(uri)) for uri in uris)
data = [fh.read().decode() for fh in resources]
print(data)
OUTPUT:
['csvcontentfollows', 'csvcontentfollows', 'csvcontentfollows']
import lxml.etree
from datauri import DataURI
tree = lxml.etree.fromstring(html_string, lxml.etree.HTMLParser())
HREF = "href"
uris = (
DataURI(item.attrib[HREF])
for item in tree.iterdescendants()
if HREF in item.attrib
)
attrs = ("mimetype", "charset", "is_base64", "data")
print([{attr: getattr(uri, attr) for attr in attrs}
for uri in uris])
OUTPUT:
[{'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}, {'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}, {'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}]
from html.parser import HTMLParser
from datauri import DataURI
uri_attrs = ("mimetype", "charset", "is_base64", "data")
class MyHTMLParser(HTMLParser):
def __init__(self):
super().__init__()
self.data = []
def handle_starttag(self, tag, attrs):
if tag == "a":
for attr, value in attrs:
if attr == "href":
for key, value in attrs:
uri = DataURI(value)
self.data.append({attr: getattr(uri, attr) for attr in uri_attrs})
parser = MyHTMLParser()
parser.feed(html_string)
print(parser.data)
OUTPUT:
[{'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}, {'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}, {'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}]