2014-03-06 52 views
8

我一直在試圖弄清楚驗證URL的最好方法是什麼(特別是在Python中),但還沒有真正能夠找到答案。似乎沒有一種已知的驗證URL的方法,並且取決於您認爲可能需要驗證的URL。另外,我發現很難找到一個易於閱讀的URL結構標準。我確實找到了RFC 3986和3987,但它們不僅包含它的結構。在Python中驗證URL

我錯過了什麼,還是沒有一個標準的方式來驗證網址?

+0

你在問什麼?你想知道一個域是否是正確的格式?你的代碼在哪裏? – Trent

+0

可能的重複[你如何在Python中使用正則表達式驗證URL?](http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular- python) – Blair

回答

13

這看起來可能是How do you validate a URL with a regular expression in Python?

重複(我會作出評論,但我沒有足夠的聲譽)。

你應該可以使用那裏描述的urlparse庫。

>>> 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有屬性爲schemenetloc

+1

您可能想要使用'rfc3987'(https://pypi.python.org/pypi/rfc3987)或對urlparse結果進行更多處理。 urlparse實際上不會將netloc驗證爲「internet網址」 - 我也因此而被咬傷。 'urlparse('http:// invalidurl')會給你一個netloc +方案。 –

+0

@JonathanVanasco,'python -c「import urlparse; print urlparse.urlparse('invalidurl')」'給出''ParseResult(scheme ='',netloc ='',path ='invalidurl',params ='',query = '',fragment ='')',所以沒有'netloc'或'scheme'。但是這對於這個問題看起來更好,因爲它也提供了驗證。 – bgschiller

+0

對不起,格式化在我原來的評論上搞砸了顯示和自動鏈接。我已經提出了'urlparse.urlparse('http:// invalidurl')' - 注意該方案已從原始方案中刪除。 'urlparse'模塊將'invalidurl'解釋爲netloc的主機名 - 這是對一般格式的正確解釋,但大多數人並不打算像這樣的東西通過。我遇到了太多的錯別字,例如'http:// example.com' - >'http:// examplecom'。如果你傳入IP地址,它不會強制執行ipv4或ipv6,所以它也會接受'999.999.999.999.999'。 –

0

假設你使用Python 3的字符串,你可以使用的urllib。該代碼將如下所示:

import urllib.request as req 
import urllib.parse as p 

def foo(): 
    url = 'http://bar.com' 
    request = req.Request(url) 
    try: 
     response = req.urlopen(request) 
     #response is now a string you can search through containing the page's html 
    except: 
     #The url wasn't valid 

如果在行「response = ...」上沒有錯誤,那麼url是有效的。

+3

這隻適用於主機有互聯網連接的情況,這可能並非總是如此。 – bgschiller

+3

最好不要使用互聯網連接來確定URL是否有效。同樣使用Python 2.7,應該在原始問題中指定。 – mp94