当前位置:   article > 正文

python获取url中的参数【python3】_python 获取url 拼接的参数

python 获取url 拼接的参数

引入模块,python3自带,无需安装

from urllib import parse
  • 1

ps:python2的urlparse包合并到python3的urllib中了


四个常用方法如下:


1.url解码

urldata = "https://kns.cnki.net/kcms/detail/detail.aspx?sfield=fn&QueryID=8&CurRec=2&DbCode=%20CJFD&dbname=CJFDAUTO&filename=BYYY202024057&urlid=&yx="

# url解码
urldata = parse.unquote(urldata)
print(urldata)   # https://kns.cnki.net/kcms/detail/detail.aspx?sfield=fn&QueryID=8&CurRec=2&DbCode= CJFD&dbname=CJFDAUTO&filename=BYYY202024057&urlid=&yx=
  • 1
  • 2
  • 3
  • 4
  • 5

2.获取IP/域名

urldata = "https://kns.cnki.net/kcms/detail/detail.aspx?sfield=fn&QueryID=8&CurRec=2&DbCode=%20CJFD&dbname=CJFDAUTO&filename=BYYY202024057&urlid=&yx="

# 获取IP/域名
result =parse.urlparse(urldata)
ip = result.netloc
print(ip)  # kns.cnki.net
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.获取全部参数的键值组成字典

urldata = "https://kns.cnki.net/kcms/detail/detail.aspx?sfield=fn&QueryID=8&CurRec=2&DbCode=%20CJFD&dbname=CJFDAUTO&filename=BYYY202024057&urlid=&yx="

# 获取全部参数的键值组成字典
result = parse.urlparse(urldata)
query_dict = parse.parse_qs(result.query)
print(query_dict)   # {'sfield': ['fn'], 'QueryID': ['8'], 'CurRec': ['2'], 'DbCode': [' CJFD'], 'dbname': ['CJFDAUTO'], 'filename': ['BYYY202024057']}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4.根据url中的某个键获取值

urldata = "https://kns.cnki.net/kcms/detail/detail.aspx?sfield=fn&QueryID=8&CurRec=2&DbCode=%20CJFD&dbname=CJFDAUTO&filename=BYYY202024057&urlid=&yx="

# 根据url中的某个键获取值
result = parse.urlparse(urldata)
query_dict = parse.parse_qs(result.query)
dbname = query_dict.get('dbname', [])
abcd = query_dict.get('abcd', [])
print(dbname)  # ['CJFDAUTO']
print(abcd)  # []   有值输出原值,没值输出自定义的值
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/73251
推荐阅读
相关标签
  

闽ICP备14008679号