Python网络编程

Python构建URL

Python构建URL详细操作教程
Python requests模块可以帮助构建URLS并动态处理URL值。可以以编程方式获取URL的任何子目录,然后可以用新值替换其中的一部分以构建新的URL。

建立网址

下面的示例使用urljoin在URL路径中获取不同的子文件夹。urljoin方法用于将新值添加到基本URL。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.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 Lidihuo
# Author by : www.lidihuo.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 Lidihuo
# Author by : www.lidihuo.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 Lidihuo
# Author by : www.lidihuo.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='')
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4