【问题标题】:unoptional protocol in entered link - py regex | requests [duplicate]输入链接中的非可选协议 - py regex |请求[重复]
【发布时间】:2021-04-11 12:54:34
【问题描述】:

问题是: 检查输入的链接是否有效,可选该链接可以输入为https://stackoverflow.com/ 和stackoverflow.com。

我试图解决它

input_url = str(input("Enter url: ")
result = re.findall(r'(http[s]?://)?\S+', input_url)

返回错误 - Invalid URL '': No schema supplied. Perhaps you meant http://?

没有urllib 或者别的什么,只能是正则表达式

完整代码:

import re, requests
from collections import Counter
from prettytable import PrettyTable

url_input = str(input("Enter url: "))

url_checked = re.findall(r'(http[s]?://)?\S+', url_input)[0] # берем первый элемент

response = requests.get(str(url_checked)) # запрос на введенную ссылку

result = re.findall( r"\"(?:http[s]?://)?([^:/\s\"]+)/?[^\"]*\"", response.text) # фильтрация ссылок

result.sort() # sorting by alphabet 

# link - https://stackoverflow.com/

pt = PrettyTable(field_names = ["word", "counter"])
pt.add_rows(list(Counter(result).most_common()))
print(pt)

【问题讨论】:

    标签: python regex url python-requests url-validation


    【解决方案1】:

    您的正则表达式似乎过于简单,无法可靠地验证 URL。我建议你使用来自here 的那个。

    【讨论】:

    • 使用我的正则表达式,google.com 之类的链接会通过,但在你的链接中使用正则表达式,它会给我错误)
    • 'google.com' 不是有效的 URL。它需要一个前缀(例如“http://”)。我只想检查input_url 是否与链接的正则表达式匹配,或者它是否与字符串'http://' + input_url 匹配。这将满足您的要求。
    • 这段代码有点老了。现在我有一个变体,如果链接没有协议,它会在链接中添加 https 或 http,然后请求接受它。但与此 google.com 将被匹配为无效
    • 代码可能是旧的,但这并不意味着它是无效的,对吧?您可以尝试添加可选的“www”或自己修改指向的正则表达式。
    猜你喜欢
    • 2012-05-17
    • 2015-07-31
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多