Python構建URL

Python requests模組可以幫助構建URLS並動態處理URL值。可以以編程方式獲取URL的任何子目錄,然後可以用新值替換其中的一部分以構建新的URL。

建立網址

下麵的示例使用urljoin在URL路徑中獲取不同的子檔夾。urljoin方法用於將新值添加到基本URL。

from requests.compat import urljoin
base='https://stackoverflow.com/questions/3764291'
print urljoin(base,'.')
print urljoin(base,'..')
print urljoin(base,'...')
print urljoin(base,'/3892299/')
url_query = urljoin(base,'?vers=1.0')
print url_query
url_sec = urljoin(url_query,'#section-5.4')
print url_sec

執行上面示例代碼,得到以下結果:

https://stackoverflow.com/questions/
https://stackoverflow.com/
https://stackoverflow.com/questions/...
https://stackoverflow.com/3892299/
https://stackoverflow.com/questions/3892299?vers=1.0
https://stackoverflow.com/questions/3892299?vers=1.0#section-5.4

分割網址

URL也可以分為多個主要地址。如下所示,使用urlparse方法分隔用於特定查詢的附加參數或附加到URL的標記。

from requests.compat import urlparse
url1 = 'https://docs.python.org/2/py-modindex.html#cap-f'
url2='https://docs.python.org/2/search.html?q=urlparse'
print urlparse(url1)
print urlparse(url2)

執行上面示例代碼,得到以下結果:

ParseResult(scheme='https', netloc='docs.python.org', path='/2/py-modindex.html', params='', query='', fragment='cap-f')
ParseResult(scheme='https', netloc='docs.python.org', path='/2/search.html', params='', query='q=urlparse', fragment='')