# Filter out URLs with any of some given file extensions

I wrote some code to filter a list of links, URLs, with multiple conditions given by file extensions. I want to remove every URL that is not an HTML file. The code is:

avoid = [".pptx", ".ppt", ".xls", ".xlsx", ".xml", ".xlt", ".pdf",
".jpg", ".png", ".svg", ".doc", ".docx", ".pps"]

"http://www.abc.com/file.png"]

def analyse_resource_extension(url):
match = [ext in url for ext in avoid]
return any(element is True for element in match)



so that links finishes with ["http://www.abc.com"] as only value. This solution seems kind of wordy for me. Is there any way to perform the same action without using the analyse_resource_extension function?

Strictly speaking, there is no direct correlation between the URL string and the type of the content you are going to get when following the URL - there can be, for instance, redirects; or the url leading to a, say, image file would not have the filename with an extension in it (example). And, keeping the list of disallowed extensions does not scale well.

An alternative, slower, but more reliable way would be to actually visit the URLs (we can use "lightweight" HEAD requests for it) and check the Content-Type header. Something like:

import requests

"http://www.abc.com/file.png"]

with requests.Session() as session:


Note that to improve on speed, we are also using the same Session object, which reuses the underlying TCP connection:

..if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase..

Demo (using httpbin):

In [1]: import requests

...:          "https://httpbin.org/image/png",
...:          "https://httpbin.org/image/svg",
...:          "https://httpbin.org/image"]

In [3]: with requests.Session() as session:
...:
['https://httpbin.org/html']


You can even take it a step further and solve it with asyncio and aiohttp:

import asyncio

import aiohttp

@asyncio.coroutine
def is_html(session, url):
response = yield from session.head(url, compress=True)

if __name__ == '__main__':
"https://httpbin.org/image/png",
"https://httpbin.org/image/svg",
"https://httpbin.org/image"]
loop = asyncio.get_event_loop()

conn = aiohttp.TCPConnector(verify_ssl=False)
with aiohttp.ClientSession(connector=conn, loop=loop) as session:
loop.run_until_complete(f)


Prints:

https://httpbin.org/image/svg False
https://httpbin.org/image False
https://httpbin.org/image/png False
https://httpbin.org/html True

• +1 much better answer than mine. Didn't know that you could determine the stuff with "Content-Type" either. – Dair Apr 3 '17 at 2:15

This solution seems kind of wordy for me. Is there any way to perform the same action without using the analyse_resource_extension function?

How about you keep analyse_resource_extension and instead use itertools.filterfalse:

from itertools import filterfalse
...