xin*_*hen 6 python url python-2.x python-3.x
我有以下网址:
https://stackoverflow.com/questions/7990301?aaa=aaa
https://stackoverflow.com/questions/7990300?fr=aladdin
https://stackoverflow.com/questions/22375#6
https://stackoverflow.com/questions/22375?
https://stackoverflow.com/questions/22375#3_1
Run Code Online (Sandbox Code Playgroud)
我需要网址,例如:
https://stackoverflow.com/questions/7990301
https://stackoverflow.com/questions/7990300
https://stackoverflow.com/questions/22375
https://stackoverflow.com/questions/22375
https://stackoverflow.com/questions/22375
Run Code Online (Sandbox Code Playgroud)
我的尝试:
url='https://stackoverflow.com/questions/7990301?aaa=aaa'
if '?' in url:
url=url.split('?')[0]
if '#' in url:
url = url.split('#')[0]
Run Code Online (Sandbox Code Playgroud)
我认为这是一种愚蠢的方式
Mat*_*ory 10
非常有用的库furl使删除查询和片段部分变得微不足道:
>>> furl.furl("https://hi.com/?abc=def#ghi").remove(args=True, fragment=True).url
https://hi.com/
Run Code Online (Sandbox Code Playgroud)
您可以拆分字符串中不存在的内容,只获取一个元素的列表,因此根据您的目标,可以执行以下操作来简化现有代码:
url = url.split('?')[0].split('#')[0]
Run Code Online (Sandbox Code Playgroud)
并不是说这是最好的方法(furl是一个很好的解决方案),但是这是一种方法。