[英]Python Code to Parse & Retrieve value from URL string
I have some Dot Net code that parses and retrieves a value from a URL string. 我有一些点网代码,可以解析并从URL字符串检索值。
However, I would like to perform the same function but now use python code instead. 但是,我想执行相同的功能,但现在改用python代码。
Dot Net code snippet is below: 点网代码段如下:
string queryString = string.Empty;
string application_id = string.Empty;
string currentURL = Browser.getDriver.Url;
Uri url = new Uri(currentURL);
string query_String = url.Query;
application_id = query_String.Split(new char[] { '=' }).Last();
Thanks in advance 提前致谢
Always best to use std lib functions if they are available. 如果可用,请始终最好使用std lib函数。 Python 3 has
urllib.parse
(if you are still on Py2, it's urlparse
). Python 3具有
urllib.parse
(如果您仍在Py2上, urlparse
)。 Use the urlparse
method of this module to extract the query part of the url (the stuff after the '?'). 使用此模块的
urlparse
方法提取URL的查询部分(“?”之后的内容)。 Then parse_qs
will convert this query to a dict of key:list
values - the values are lists to handle query strings that have repeated keys. 然后
parse_qs
将此查询转换为key:list
值的字典-值是用于处理具有重复键的查询字符串的列表。
url = 'http://www.somesite.blah/page?id=12345&attr=good&attr=bad&attr=ugly'
try:
from urllib.parse import urlparse, parse_qs
except ImportError:
# still using Python 2? time to move up
from urlparse import urlparse, parse_qs
parts = urlparse(url)
print(parts)
query_dict = parse_qs(parts.query)
print(query_dict)
print(query_dict['id'][0])
prints: 印刷品:
ParseResult(scheme='http', netloc='www.somesite.blah', path='/page', params='',
query='id=12345&attr=good&attr=bad&attr=ugly', fragment='')
{'attr': ['good', 'bad', 'ugly'], 'id': ['12345']}
12345
首先,最后= query_String.split('=')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.