Python - 構建 URL



Requests 模組可以幫助我們構建 URL 並動態地操作 URL 值。可以以程式設計方式獲取 URL 的任何子目錄,然後用新值替換其中的一部分以構建新的 URL。

Build_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,'/3764299/')
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/3764299/
https://stackoverflow.com/questions/3764291?vers=1.0
https://stackoverflow.com/questions/3764291?vers=1.0#section-5.4

拆分 URL

除了主地址外,還可以將 URL 拆分為很多部分。如下所示,附加的引數(用於特定查詢或附加到 URL 上的標記)透過使用 urlparse 方法來拆分。

from requests.compat import urlparse
url1 = 'https://docs.python.club.tw/2/py-modindex.html#cap-f'
url2='https://docs.python.club.tw/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='')
廣告