从URL python中删除HTTP和WWW
如何在Python中从url中剥离从URL python中删除HTTP和WWW,python,url,Python,Url,如何在Python中从url中剥离http和www?您可以使用regex url1='www.google.com' url2='http://www.google.com' url3='http://google.com' url4='www.google' url5='http://www.google.com/images' url6='https://www.youtube.com/watch?v=6RB89BOxaYY 或者您可以使用正则表达式 url = 'http://www.g
http
和www
?您可以使用regex
url1='www.google.com'
url2='http://www.google.com'
url3='http://google.com'
url4='www.google'
url5='http://www.google.com/images'
url6='https://www.youtube.com/watch?v=6RB89BOxaYY
或者您可以使用正则表达式
url = 'http://www.google.com/images'
url = url.replace("http://www.","")
print url
可以使用正则表达式,具体取决于数据的严格程度。http和www会一直存在吗?您是否考虑过https或w3站点
import re
url = re.compile(r"https?://(www\.)?")
url.sub('', 'http://www.google.com/images').strip().strip('/')
1不损害以w结尾的网站
澄清后编辑
我要做两个步骤:
import re
new_url = re.sub('.*w\.', '', url, 1)
更优雅的解决方案是使用urlparse:
if url.startswith('http'):
url = re.sub(r'https?:\\', '', url)
if url.startswith('www.'):
url = re.sub(r'www.', '', url)
第一个选项包括
https
或http
,具体取决于链接,第二部分netloc
包括您要查找的内容。“http://www.google.com/images“[11::
那么您希望输出什么呢?后面的元素是参数(也称为查询
)-uparse可以将其保存在单独的变量中。我希望输出没有http(s),wwwhttp将始终存在。www可能是也可能不是。有时它也可能是https?在这种情况下,我应该如何修改上面的代码来删除https?如果url.startswith('http'):new_url=re.sub('.*w\,'',url,1)如果我也想删除https,我的第二个答案适合您的任何要求
from urllib.parse import urlparse
def get_hostname(url, uri_type='both'):
"""Get the host name from the url"""
parsed_uri = urlparse(url)
if uri_type == 'both':
return '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
elif uri_type == 'netloc_only':
return '{uri.netloc}'.format(uri=parsed_uri)