pie*_*eca 5 html python regex hyperlink
如何检查给定的链接(URL)是指向文件还是另一个网页?
我的意思是:
目前,我正在做一个非常棘手的多步骤检查,它还需要相对于绝对链接进行转换,如果缺少则添加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
Run Code Online (Sandbox Code Playgroud)
是否有一个干净的,单一的正则表达式匹配解决方案来解决此问题,或者有一个具有确定功能的库来解决此问题?我想一定有人在我之前遇到了这个问题,但是不幸的是,我在这里找不到解决方案。
Aran-Fey 的答案在表现良好的页面上效果很好,这些页面占网络的 99.99%。但没有任何规则规定以特定扩展名结尾的 URL 必须解析为特定类型的内容。配置不当的服务器可能会为名为“example.png”的页面的请求返回 html,或者可能为名为“example.php”的页面返回 mpeg,或者内容类型和文件扩展名的任何其他组合。
获取 URL 内容类型信息的最准确方法是实际访问该 URL 并检查其标头中的内容类型。大多数 http 接口库都有一种仅从站点检索标头信息的方法,因此即使对于非常大的页面,此操作也应该相对较快。例如,如果您正在使用requests,您可能会这样做:
import requests
def get_content_type(url):
response = requests.head(url)
return response.headers['Content-Type']
test_cases = [
"http://www.example.com",
"https://i.stack.imgur.com/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))
Run Code Online (Sandbox Code Playgroud)
结果:
Url: http://www.example.com
Content type: text/html; charset=UTF-8
Url: https://i.stack.imgur.com/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
Run Code Online (Sandbox Code Playgroud)