【问题标题】:How to check the url is either web page link or file link in python如何检查网址是网页链接还是python中的文件链接
【发布时间】:2014-02-26 05:10:08
【问题描述】:

假设我有如下链接:

    http://example.com/index.html
    http://example.com/stack.zip
    http://example.com/setup.exe
    http://example.com/news/

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

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

是否有任何标准方法来区分文件 url 或网页链接? 提前致谢。

【问题讨论】:

  • 通过HTTP响应的Content-Type,也可以通过url扩展,如htmlzipexe
  • @Omid Raha:我期待一些内置函数来检查这个
  • 好的,请检查我的答案。

标签: python file url web hyperlink


【解决方案1】:
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

演示:

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))

输出:

text/html
image/x-png
text/html
application/ogg

【讨论】:

  • 你也可以使用response.headers.get_content_type()
【解决方案2】:
import urllib
mytest = urllib.urlopen('http://www.sec.gov')
mytest.headers.items()

('content-length', '20833'), ('expires', 'Sun, 02 Feb 2014 19:36:12 GMT'), ('server', 'SEC'), ('connection', 'close'), ('cache-control', 'max-age=0'), ('date', 'Sun, 02 Feb 2014 19:36:12 GMT'), ('content-type', 'text/html')]

mytest.headers.items() 是一个元组列表,您可以在我的示例中看到列表中的最后一项描述了内容

我不确定长度是否会变化,因此您可以遍历它以找到具有 '内容类型'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多