解析 URL 查询字符串的最佳方法 [英] Best way to parse a URL query string

查看:30
本文介绍了解析 URL 查询字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中从 URL 查询字符串(例如,通过表单附加到 URL 的数据)中解析数据的最佳方法是什么?我的目标是接受表单数据并将其显示在同一页面上.我研究了几种并不是我想要的方法.

What is the best way to parse data out of a URL query string (for instance, data appended to the URL by a form) in python? My goal is to accept form data and display it on the same page. I've researched several methods that aren't quite what I'm looking for.

我正在创建一个简单的网络服务器,目的是学习套接字.此网络服务器不会用于测试目的.

I'm creating a simple web server with the goal of learning about sockets. This web server won't be used for anything but testing purposes.

GET /?1pm=sample&2pm=&3pm=&4pm=&5pm= HTTP/1.1
Host: localhost:50000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://localhost:50000/?1pm=sample&2pm=&3pm=&4pm=&5pm=

推荐答案

这里是一个使用python3的例子urllib.parse:

Here is an example using python3 urllib.parse:

from urllib.parse import urlparse, parse_qs
URL='https://someurl.com/with/query_string?i=main&mode=front&sid=12ab&enc=+Hello'
parsed_url = urlparse(URL)
parse_qs(parsed_url.query)

输出:

{'i': ['main'], 'enc': [' Hello '], 'mode': ['front'], 'sid': ['12ab']}

python2注意事项:from urlparse import urlparse, parse_qs

Note for python2: from urlparse import urlparse, parse_qs

见:https://pythonhosted.org/six/#module-六.moves.urllib.parse

这篇关于解析 URL 查询字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆