我一直在尝试找出验证 URL 的最佳方法(特别是在 Python 中),但一直未能真正找到答案。似乎没有一种已知的方法来验证 URL,这取决于您认为可能需要验证哪些 URL。同样,我发现很难找到一个易于阅读的 URL 结构标准。我确实找到了 RFC 3986 和 3987,但它们包含的内容远不止其结构。
我是不是遗漏了什么,或者是否没有一种标准的方法来验证 URL?
最佳答案
这看起来可能是 How do you validate a URL with a regular expression in Python? 的副本
您应该能够使用此处描述的 urlparse
库。
>>> from urllib.parse import urlparse # python2: from urlparse import urlparse
>>> urlparse('actually not a url')
ParseResult(scheme='', netloc='', path='actually not a url', params='', query='', fragment='')
>>> urlparse('http://google.com')
ParseResult(scheme='http', netloc='google.com', path='', params='', query='', fragment='')
在要检查的字符串上调用 urlparse
,然后确保 ParseResult
具有 scheme
和 netloc< 的属性
关于python - 在 Python 中验证 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22238090/