XZ_Python之数组和url操作
程序员文章站
2024-02-18 12:11:04
...
for循环打印数组的元素和索引
法一:先计算出数组的长度,然后for循环索引,获取索引对应的元素
url_array = ["http:www.baidu.com","http:www.suning.com","http:www.jd.com"]
for i in range(len(url_array)):
print("\n第%d个值:" % i, url_array[i])
# 打印结果
第0个值: http:www.baidu.com
第1个值: http:www.suning.com
第2个值: http:www.jd.com
法二:使用enumerate函数实现
url_array = ["http:www.baidu.com","http:www.suning.com","http:www.jd.com"]
for i, value in enumerate(url_array):
print("\n第%d个字典值:" % i, value)
# 打印结果
第0个值: http:www.baidu.com
第1个值: http:www.suning.com
第2个值: http:www.jd.com
获取url地址?后面的参数
法一:先根据?和&符号分隔出数据,然后再以=分隔字符串,前面的值赋值给key,后面的赋值给value
def querys_params(url):
index = url.find('?')
if index == -1:
return url, {}
else:
url, query_string = url.split('?', 1)
args = query_string.split('&')
query = {}
for arg in args:
k, v = arg.split('=')
query[k] = v
return url, query
url_array = ["http:www.baidu.com?a=2&b=4&mid=ui","http:www.suning.com?user=2&id=4&mid=ui","http:www.jd.com?pid=134&huiyuan=1"]
for i in range(len(url_array)):
params = querys_params(url_array[i])
print("\n第%d个字典值:"%i,params)
结果:
第0个字典值: ('http:www.baidu.com', {'a': '2', 'b': '4', 'mid': 'ui'})
第1个字典值: ('http:www.suning.com', {'user': '2', 'id': '4', 'mid': 'ui'})
第2个字典值: ('http:www.jd.com', {'pid': '134', 'huiyuan': '1'})
法二:利用urlparse的parse_qs方法
def querys_params(url):
qy = urlparse(url).query
item = urllib.parse.parse_qs(qy).items()
return dict([(k, v[0]) for k, v in item])
url_array = ["http:www.baidu.com?a=2&b=4&mid=ui","http:www.suning.com?user=2&id=4&mid=ui","http:www.jd.com?pid=134&huiyuan=1"]
for i in range(len(url_array)):
params = querys_params(url_array[i])
print("\n第%d个字典值:"%i,params)
结果:
第0个字典值: {'a': '2', 'b': '4', 'mid': 'ui'}
第1个字典值: {'user': '2', 'id': '4', 'mid': 'ui'}
第2个字典值: {'pid': '134', 'huiyuan': '1'}
TypeError:'list' object is not callable
遇到问题:TypeError:'list' object is not callable
原因是url链接中&符号写成了?,例如:http:www.baidu.com?a=2&b=4&mid=ui 写成了http:www.baidu.com?a=2?b=4&mid=ui
上一篇: python实现的多线程端口扫描功能示例
下一篇: JSP中何获取properties中的值