「Python URLエンコード」の版間の差分
ナビゲーションに移動
検索に移動
| 1行目: | 1行目: | ||
==Python URLエンコード== | ==Python URLエンコード== | ||
| − | [[Python]]{{category 文字化け}} | + | [[Python]] | {{category 文字化け}} |
*http://d.hatena.ne.jp/niiyan/20090509/1241884365 | *http://d.hatena.ne.jp/niiyan/20090509/1241884365 | ||
*http://hogeo.jp/blog/memo/2007/11/pythonurlliburlencode.html | *http://hogeo.jp/blog/memo/2007/11/pythonurlliburlencode.html | ||
2020年2月15日 (土) 08:38時点における版
目次
Python URLエンコード
- http://d.hatena.ne.jp/niiyan/20090509/1241884365
- http://hogeo.jp/blog/memo/2007/11/pythonurlliburlencode.html
urllib
urllib.quote
構文
quote(s, safe='/')
- safe にエンコードしない文字を指定
- safeで指定しなければ、すべてエンコードする
- RFC 2396 Uniform Resource Identifiers (URI): Generic Syntaxでの予約、非予約文字
予約文字
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
非予約文字
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
区切り文字
delims = "<" | ">" | "#" | "%" | <">
安全でない
unwise = "{" | "}" | "|" | "\" | "^" | "[ " " ]" | "`"
例1
>>> import urllib
>>> urllib.quote('abc def')
'abc%20def'
例2
>>> urllib.quote('http://test.com?p=abc def')
'http%3A//test.com%3Fp%3Dabc%20def'
例3
>>> urllib.quote('http://test.com?p=abc def', safe=';/?:@&=+$,')
'http://test.com?p=abc%20def'
urllib.urlencode
- タプル、またはディクショナリを、URL クエリー文字列として生成する
>>> import urllib
>>> param = {'q':'test', 'id':'piroto'}
>>> urllib.urlencode(param)
'q=test&id=piroto'
HTML特殊文字のエスケープ、アンエスケープ
- xml.sax.saxutils の escape, unescape を利用すると便利
>>> from xml.sax.saxutils import *
>>> escape("<&>")
'<&>'
>>> unescape("<&>")
'<&>'
>>> unescape("'",{"'":"'"})
"'"
© 2006 矢木浩人