【发布时间】:2019-07-29 09:39:13
【问题描述】:
如何检查给定的链接(url)是指向文件还是另一个网页?
我的意思是:
- 页面:https://stackoverflow.com/questions/
- 页面:https://www.w3schools.com/html/default.asp
- 文件:https://www.python.org/ftp/python/3.7.2/python-3.7.2.exe
- 文件:http://jmlr.org/papers/volume19/16-534/16-534.pdf#page=15
目前我正在做一个非常hacky的多步骤检查,它还需要相对于绝对链接进行转换,如果丢失则添加http前缀并删除'#'锚链接/参数才能工作。我也不确定我是否将所有可能存在的页面扩展列入白名单。
import re
def check_file(url):
try:
sub_domain = re.split('\/+', url)[2] # part after '2nd slash(es)''
except:
return False # nothing = main page, no file
if not re.search('\.', sub_domain):
return False # no dot, no file
if re.search('\.htm[l]{0,1}$|\.php$|\.asp$', sub_domain):
return False # whitelist some page extensions
return True
tests = [
'https://www.stackoverflow.com',
'https://www.stackoverflow.com/randomlink',
'https:////www.stackoverflow.com//page.php',
'https://www.stackoverflow.com/page.html',
'https://www.stackoverflow.com/page.htm',
'https://www.stackoverflow.com/file.exe',
'https://www.stackoverflow.com/image.png'
]
for test in tests:
print(test + '\n' + str(check_file(test)))
# False: https://www.stackoverflow.com
# False: https://www.stackoverflow.com/randomlink
# False: https:////www.stackoverflow.com//page.php
# False: https://www.stackoverflow.com/page.html
# False: https://www.stackoverflow.com/page.htm
# True: https://www.stackoverflow.com/file.exe
# True: https://www.stackoverflow.com/image.png
是否有针对此问题的干净、单一的正则表达式匹配解决方案或具有已建立功能的库来解决此问题?我想一定有人在我之前遇到过这个问题,但不幸的是我在 SO 上找不到解决方案。
【问题讨论】:
-
我认为你不能仅仅通过查看 url 就可以明确地确定 url 将为你提供的数据类型。如果 Web 服务器真的想要,它可以决定在您访问“image.png”时提供一个 html 文件。或者,当您转到“page.htm”时,它可以提供 mp3。或文件类型和扩展名的任何其他组合。要获得准确的类型数据,您需要检查 http 标头的 MIME 类型。
-
谢谢@Kevin,显然我一直在尝试解决错误的问题。我想我会按照你的建议去做
标签: python html regex hyperlink