如何检查用户输入的字符串是否是Python中的URL或纯文本

时间:2016-10-21 16:07:14

标签: python url

  1. 我想从用户输入一个字符串并检查它是URL还是某些文本,我应该在字符串上使用 condition
  2. 此外,如果字符串不是URL,则用Google搜索
  3. 我已经在浏览器中打开URL的部分,但我对条件感到困惑,我可以使用

    if "http://" in input
    

    但是如果用户不想指定协议怎么办。

4 个答案:

答案 0 :(得分:1)

validate = URLValidator()

try:
    validate("http://www.avalidurl.com/")
    print("String is a valid URL")
except ValidationError as exception:
    print("String is not valid URL")

Source

答案 1 :(得分:0)

只是测试它

possible_url = user_input
if not possible_url.lower().startswith("http"): possible_url = "HTTP://%s"%possible_url
if 199 < requests.get(possible_url).status_code < 400: print "OK thats a url!

答案 2 :(得分:0)

我会使用urlparse.urlparse()并测试方案的存在,如下所示:

if urlparse.urlparse(user_data).scheme:
    print "That's a URL"

答案 3 :(得分:0)

您可以使用Python - How to validate a url in python ? (Malformed or not)中提到的正则表达式:

array()