如何检查网址是在python中的网页链接或文件链接 [英] How to check the url is either web page link or file link in python
本文介绍了如何检查网址是在python中的网页链接或文件链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
http://example.com/index.html
在上面的链接中,第一和第四个链接是网页链接,第二个和第三个链接是文件链接。
http ://example.com/stack.zip
http://example.com/setup.exe
http://example.com/news/
这些只是文件链接的一些例子,即.zip和.exe,但可能有很多其他文件。
有没有任何标准的方法来区分文件的网址或网页链接?
在此先感谢。
解决方案
import urllib
import mimetypes
$ b def guess_type_of(link,strict = True):
link_type,_ = mimetypes.guess_type(link)
如果link_type为None且严格:
u = urllib.urlopen(link)
link_type = u.headers.gettype()#或使用:u.info()。gettype()
返回link_type
演示:
links = ['http ://stackoverflow.com/q/21515098/538284',#这是一个html页面
'http://upload.wikimedia.org/wikipedia/meta/6/6d/Wikipedia_wordmark_1x.png',#这是一个png文件
'http://commons.wikimedia.org/wiki/File:Typing_example.ogv',#这是一个html页面
'http://upload.wikimedia.org/wikipedia/commons/ e / e6 / Typing_example.ogv'#这是一个ogv文件
]
链接链接:
print(guess_type_of(link))
输出: p>
text / html
image / x-png
text / html
application / ogg
Suppose i have links as follows:
http://example.com/index.html http://example.com/stack.zip http://example.com/setup.exe http://example.com/news/
In the above links first and fourth links are web page links and second and third are the file link.
These are only some examples of files links i.e .zip and .exe, but there may be many other files.
Is there any standard way to distinguish between file url or web page link? Thanks in advance.
解决方案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
Demo:
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))
Output:
text/html image/x-png text/html application/ogg
这篇关于如何检查网址是在python中的网页链接或文件链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文