實例刪除URL查詢字符串:如何使用Python
http://example.com/?a=text&q2=text2&q3=text3&q2=text4
取出後 「Q2」,則回覆:
http://example.com/?q=text&q3=text3
在這種情況下,出現了多個「 q2「並且全部被刪除。
謝謝
實例刪除URL查詢字符串:如何使用Python
http://example.com/?a=text&q2=text2&q3=text3&q2=text4
取出後 「Q2」,則回覆:
http://example.com/?q=text&q3=text3
在這種情況下,出現了多個「 q2「並且全部被刪除。
謝謝
import cgi
import urlparse
url = "http://example.com/?a=text&q2=text2&q3=text3&q2=text4"
qs = cgi.parse_qs(urlparse.urlparse(url)[4])
del(qs['q2'])
print qs
明確...
>>> import cgi
>>> import urlparse
>>> url = "http://example.com/?a=text&q2=text2&q3=text3&q2=text4"
>>> qs = cgi.parse_qs(urlparse.urlparse(url)[4])
>>> del(qs['q2'])
>>> print qs
{'a': ['text'], 'q3': ['text3']}
>>>
#!/usr/bin/env python
from urllib import urlencode
from urlparse import urlparse, urlunparse, parse_qs
url = 'http://example.com/?a=text&q2=text2&q3=text3&q2=text4'
u = urlparse(url)
query = parse_qs(u.query)
query.pop('q2', None)
u = u._replace(query=urlencode(query, True))
print(urlunparse(u))
import re
q ="http://example.com/?a=text&q2=text2&q3=text3&q2=text4"
todelete="q2"
#Delete every query string matching the pattern
r = re.sub(r''+todelete+'=[a-zA-Z_0-9]*\&*',r'',q)
#Delete the possible trailing #
r = re.sub(r'&$',r'',r)
print r
現在你有2個問題。 –
import urlparse
url = 'http://example.com/?a=text&q2=text2&q3=text3&q2=text4'
urlparse.urljoin(url, urlparse.urlparse(url).path)
使用Python的URL處理庫捲起:
import furl
f = furl.furl("http://example.com/?a=text&q2=text2&q3=text3&q2=text4")
f.remove(['q2'])
print(f.url)
結束後首先查找查詢字符串('urlparse.urlparse(url)[4]'),然後簡單地在'&'上分開,檢查對於每個參數,如果它以「q2 =」開頭並將其從查詢字符串中移除。加入他們'&'。這也是維護秩序,這也是我的要求。只是想在7年後添加我的幾分錢。 – YnkDK