Python 构建 URL


requests 模块可以帮助我们构建 URL 并动态操作 URL 值。可以通过编程方式获取 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,'/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.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='')