【问题标题】:Remove GET variables from URL in python从 python 中的 URL 中删除 GET 变量
【发布时间】:2012-12-22 10:11:38
【问题描述】:

我有这个网址:

http://www.exmaple.com/boo/a.php?a=jsd

我想要的输出是这样的:

http://www.exmaple.com/boo/

如果我有

http://www.exmaple.com/abc.html

应该是

http://www.exmaple.com/

http://www.exmaple.com/

应该返回

http://www.exmaple.com/

没有任何变化

这是我尝试过的

re.sub(r'\?[\S]+','',"http://www.exmaple.com/boo/a.php?a=jsd")

但它会返回

http://www.exmaple.com/boo/a.php

有什么建议可以做些什么来获得正确的输出,或者有没有人有更好的想法来完成这个?

【问题讨论】:

  • urlparse module 不够好吗?
  • 是不是故意到处都是“例子”?
  • @MartijnPieters 是的 url 解析是我需要的!谢谢

标签: python regex algorithm url python-2.7


【解决方案1】:

请像这样使用 stdlib urlparse 模块。一般来说,除非绝对必要,否则我会尽量避免使用正则表达式。

from urlparse import urlparse, urlunparse
>>> parsed = urlparse("http://www.exmaple.com/boo/a.php?a=jsd")
>>> scheme, netloc, path, params, query, fragment = parsed
>>> urlunparse((scheme,netloc,path.split('/')[1],'','',''))
'http://www.exmaple.com/boo'

【讨论】:

  • 是的,但是,path.split 部分需要一些调整(查看http://www.exmaple.com/)。
【解决方案2】:

我会这样做:

>>> import re
>>> url = "http://www.exmaple.com/boo/a.php?a=jsd"
>>> url[:url.rfind("/")+1]
'http://www.exmaple.com/boo/'

删除最后一个“/”之后的所有内容。我不确定它是否涵盖所有特殊情况...

编辑:使用urlparse 和我的简单rfind 的新解决方案:

import re, urlparse
def url_cutter(url):
    up = urlparse.urlparse(url)
    url2 = up[0]+"://"+up[1]+up[2]
    if url.rfind("/")>6:
            url2 = url2[:url2.rfind("/")+1]
    return url2

然后:

In [36]: url_cutter("http://www.exmaple.com/boo/a.php?a=jsd")
Out[36]: 'http://www.exmaple.com/boo/'

In [37]: url_cutter("http://www.exmaple.com/boo/a.php?a=jsd#dvt_on")
Out[37]: 'http://www.exmaple.com/boo/'

In [38]: url_cutter("http://www.exmaple.com")
Out[38]: 'http://www.exmaple.com'

【讨论】:

  • 确实@MevinBabu,可以添加一个像if url.rfind("/")>6 这样的简单测试来避免这种情况。
  • 如果url有#fragment/with/slashes则失败
  • 感谢您指出@J.F.Sebastian,我编辑了我的答案以更正它。
【解决方案3】:

可能有一种更优化的方法来做到这一点,但有了这个,您就不需要晦涩的导入或第三方包。

url = "http://www.google.com/abc/abc.html?q=test"
cleaned_url = url[:url.rindex("?")]
cleaned_url = cleaned_url.split("/")
cleaned_url = [item for item in cleaned_url if ".html" not in item]
cleaned_url = "/".join(cleaned_url)

【讨论】:

  • 您可能想测试 url.rindex 是否会在“?”的情况下向您发送错误消息。字符串中不存在
猜你喜欢
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-03
  • 2022-08-18
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
相关资源
最近更新 更多