python - 正则表达式检查链接是否指向文件

标签 python html regex hyperlink

如何检查给定的链接(url)是指向文件还是指向另一个网页?

我的意思是:

目前,我正在通过一个相当棘手的多步骤检查来完成它,它还需要相对于绝对链接进行转换,如果缺少则添加 http 前缀并删除“#” anchor 链接/参数才能工作。我也不确定我是否将所有可能存在的页面扩展列入白名单

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 或其他地方找到解决方案。

最佳答案

Aran-Fey 的答案适用于行为良好的页面,这些页面占网络的 99.99%。但是没有规则说以特定扩展名结尾的 url 必须解析为特定类型的内容。配置不当的服务器可能会针对名为“example.png”的页面的请求返回 html,或者它可能会针对名为“example.php”的页面返回 mpeg,或任何其他内容类型和文件扩展名的组合。

获取 URL 内容类型信息的最准确方法是实际访问该 URL 并检查其 header 中的内容类型。大多数 http 接口(interface)库都有办法只从站点检索 header 信息,因此即使对于非常大的页面,此操作也应该相对较快。例如,如果您正在使用 requests,您可能会这样做:

import requests
def get_content_type(url):
    response = requests.head(url)
    return response.headers['Content-Type']

test_cases = [
    "http://www.example.com",
    "/image/T3HH6.png?s=328&g=1",
    "http://php.net/manual/en/security.hiding.php",
]    

for url in test_cases:
    print("Url:", url)
    print("Content type:", get_content_type(url))

结果:

Url: http://www.example.com
Content type: text/html; charset=UTF-8
Url: /image/T3HH6.png?s=328&g=1
Content type: image/png
Url: http://php.net/manual/en/security.hiding.php
Content type: text/html; charset=utf-8

关于python - 正则表达式检查链接是否指向文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55044852/

相关文章:

容器中文本的 Css 在新行上继续并让容器向下扩展我有必要吗?

PHP 表单到电子邮件 - 电子邮件仅包含来自已填写字段的数据

Python递归方法调用super

python - 在 Windows 中链接库

html - vertical-align 不将 list-style-image 与文本对齐

regex - 如何在 Linux 中查找和替换正则表达式模式?

javascript - 用于文本提取的正则表达式

regex - 如何在文件夹中的xml文件中grep一个词

python - 使用 Paramiko、Python 时不支持 Errno -8 Servname

python - 按成员在另一个列表中的顺序对列表元素进行分组