如何检查URL是Python中的网页链接还是文件链接

Bis*_*ash 4 python url file hyperlink web

假设我有如下链接:

    http://example.com/index.html
    http://example.com/stack.zip
    http://example.com/setup.exe
    http://example.com/news/
Run Code Online (Sandbox Code Playgroud)

在以上链接中,第一个和第四个链接是网页链接,第二个和第三个链接是文件链接。

这些只是文件链接(例如.zip和.exe)的一些示例,但可能还有许多其他文件。

有什么标准方法可以区分文件URL或网页链接吗?提前致谢。

Omi*_*aha 5

import urllib
import mimetypes


def guess_type_of(link, strict=True):
    link_type, _ = mimetypes.guess_type(link)
    if link_type is None and strict:
        u = urllib.urlopen(link)
        link_type = u.headers.gettype() # or using: u.info().gettype()
    return link_type
Run Code Online (Sandbox Code Playgroud)

演示:

links = ['http://stackoverflow.com/q/21515098/538284', # It's a html page
         'http://upload.wikimedia.org/wikipedia/meta/6/6d/Wikipedia_wordmark_1x.png', # It's a png file
         'http://commons.wikimedia.org/wiki/File:Typing_example.ogv', # It's a html page
         'http://upload.wikimedia.org/wikipedia/commons/e/e6/Typing_example.ogv'   # It's an ogv file
]

for link in links:
    print(guess_type_of(link))
Run Code Online (Sandbox Code Playgroud)

输出:

text/html
image/x-png
text/html
application/ogg
Run Code Online (Sandbox Code Playgroud)