给定一个网址字符串,要求给出网址中网站主页的地址。 提供网站 URL,您需要删除 URL 的协议并仅打印主页 URL。 输入 输入为一行行的网址字符串 输入将有多行 String,代表 URL 输出 输出网址中网站主页的地址。 仅打印每个 URL 的主页 URL
时间: 2024-10-21 10:18:43 浏览: 245
给定一个网址字符串,首先解析该URL以提取主机名部分(通常出现在"//"之后,直到最后一个"/"之前),这通常是主页的地址。例如,如果输入的是 "https://www.example.com/path/to/home", 主页地址就是 "www.example.com"。我们只需要去掉协议(如http或https)以及路径(如果有的话)。这里是一个简单的步骤:
- 使用正则表达式分割URL,获取域名部分。
- 如果域名以"/"结尾,表示这是一个相对URL,需要添加默认协议(如"//www.")前缀。
- 打印处理后的主页地址。
以下是伪代码形式:
def get_homepage_url(url):
# 使用正则表达式匹配域名
pattern = r'(?:http|https)://([^/]+)'
match = re.match(pattern, url)
if not match:
return None # 如果没有找到有效的域名,返回None
homepage = match.group(1) # 获取域名部分
if homepage.endswith('/'):
homepage += 'www.' # 添加默认前缀
return homepage
# 示例:
url = "https://www.example.com/path/to/home"
print(get_homepage_url(url)) # 输出: www.example.com
# 处理多行输入
for line in input_urls.split('\n'):
print(get_homepage_url(line))
相关推荐



















