V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
laoyuan
V2EX  ›  Python

怎样将 url 中非 ASCII 字符的部分 urlencode, UTF-8 环境

  •  
  •   laoyuan ·
    laoyuan · 2015-07-19 15:14:10 +08:00 · 2435 次点击
    这是一个创建于 3175 天前的主题,其中的信息可能已经有所发展或是发生改变。
    url = 'http://doman.com/中文' #有些不太正规的网站url 就是这样任性的

    得到 http://doman.com/%E4%B8%AD%E6%96%87

    urllib.quote( )不行,误伤冒号了
    第 1 条附言  ·  2015-07-19 16:36:25 +08:00
    误伤url 中所有需要转义的非字母ASCII字符
    5 条回复    2015-07-23 14:22:40 +08:00
    lixia625
        1
    lixia625  
       2015-07-19 16:04:40 +08:00
    先把 http:// 拿走
    laoyuan
        2
    laoyuan  
    OP
       2015-07-19 16:39:26 +08:00
    @lixia625 误伤太多,比如 url = 'http://domain.com/?中文&+,' 见 rfc3986
    kaneg
        3
    kaneg  
       2015-07-22 15:12:18 +08:00
    reserved = ';/:@&=+$,'
    print urllib.quote(url, reserved)

    不过奇怪的是,唯独?不能加入reserved,否则中文都变成?了
    laoyuan
        4
    laoyuan  
    OP
       2015-07-22 15:18:18 +08:00   ❤️ 1
    @kaneg 不止这些字符,~ 在url 里也很常见。我感觉应该有什么包可以,反正粘到浏览器地址栏里,浏览器可以正确的转义
    jack139
        5
    jack139  
       2015-07-23 14:22:40 +08:00
    好像有个urllib.quote_plus,或是urllib2,记不清了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1547 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:11 · PVG 01:11 · LAX 10:11 · JFK 13:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.