Python 构建URL
Python requests模块可以帮助构建URLS并动态处理URL值。可以以编程方式获取URL的任何子目录,然后可以用新值替换其中的一部分以构建新的URL。
建立网址
下面的示例使用urljoin在URL路径中获取不同的子文件夹。urljoin方法用于将新值添加到基本URL。
# Filename : example.py
# Copyright : 2020 By Codebaoku
# Author by : www.codebaoku.com
# Date : 2020-08-25
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
执行上面示例代码,得到以下结果:
# Filename : example.py
# Copyright : 2020 By Codebaoku
# Author by : www.codebaoku.com
# Date : 2020-08-25
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的标记。
# Filename : example.py
# Copyright : 2020 By Codebaoku
# Author by : www.codebaoku.com
# Date : 2020-08-25
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)
执行上面示例代码,得到以下结果:
# Filename : example.py
# Copyright : 2020 By Codebaoku
# Author by : www.codebaoku.com
# Date : 2020-08-25
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='')
通常,与网页的交互需要一些数据通过html页面中的表单提交给服务器。这些网络表单通常用于诸如注册新帐户或提供一些信息(例如姓名或卷号)以检索检查结果的过程。requests模块使用带有所需参数的POST方法优雅 ...