如何使用 Python 从 URL 中删除查询字符串
示例:
http://example.com/?a=text&q2=text2&q3=text3&q2=text4
删除“q2”后,返回:
http://example.com/?q=text&q3=text3
本例中,“q2”有多个,均已删除。
Example:
http://example.com/?a=text&q2=text2&q3=text3&q2=text4
After removing "q2", it will return:
http://example.com/?q=text&q3=text3
In this case, there were multiple "q2" and all have been removed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
要删除所有查询字符串参数:
对于 Python2,请将导入替换为:
To remove all query string parameters:
For Python2, replace the import with:
输出:
Output:
这不就是按一个字符分割字符串的问题吗?
Isn't this just a matter of splitting a string on a character?
使用python的url操作库furl:
Using python's url manipulation library furl:
或者简单地说,只需使用
w3lib.url
中的url_query_cleaner()
输出:
http://example.com/?a=text&q3=text3
Or simply put, just use
url_query_cleaner()
fromw3lib.url
Output:
http://example.com/?a=text&q3=text3
您可以用来更好地控制您想要执行的操作的另一种方法是 urlunparse() ,它采用从 urlparse() 返回的部分的元组。
例如,最近我需要更改路径但保留查询:
此方法保留所有 URL,并为您提供对要保留、更改和删除的内容的精细控制。
Another method that you can use to have more control over what you want to do is
urlunparse()
which takes a tuple of the parts returned fromurlparse()
.For example, recently I needed to change the path but keep the query:
This method preserves all of the URL and gives you granular control of what you want to keep, change, and remove.
或者你可以只使用带
Or you could just use strip