首页 > 解决方案 > 使用 urlsplit 从 url 中获取域名

问题描述

我有一个数据集,其中包含不同形式的 url(例如https://stackoverflow.com, https://www.stackoverflow.com, stackoverflow.com),我只需要像stackoverflow.

我使用了parse.urlsplit(url)fromurllib但在我的情况下效果不佳。

我怎样才能只获得域名?

编辑。:

我的代码:

def normalization (df):
  df['after_urlsplit'] = df["httpx"].map(lambda x: parse.urlsplit(x))
  return df

normalization(df_sample)

输出:

            httpx                       after_urlsplit
0   https://stackoverflow.com/       (https, stackoverflow.com, /, , )
1   https://www.stackoverflow.com/   (https, www.stackoverflow.com, /, , )
2   www.stackoverflow.com/           (, , www.stackoverflow.com/, , )
3   stackoverflow.com/               (, , stackoverflow.com/, , )

标签: pythondataseturllib

解决方案


新答案,也适用于网址和主机名

要处理没有协议定义的实例(例如example.com),最好使用正则表达式:

import re

urls = ['www.stackoverflow.com',
        'stackoverflow.com',
        'https://stackoverflow.com',
        'https://www.stackoverflow.com/',
        'www.stackoverflow.com',
        'stackoverflow.com',
        'https://subdomain.stackoverflow.com/']

for url in urls:
    host_name = re.search("^(?:.*://)?(.*)$", url).group(1).split('.')[-2]
    print(host_name)

stackoverflow这在所有情况下都会打印。

旧答案,仅适用于网址

您可以使用netlocurlsplit 返回的值,另外通过一些额外的定制来获得您想要的域(部分):

from urllib.parse import urlsplit

m = urlsplit('http://subdomain.example.com/some/extra/things')

print(m.netloc.split('.')[-2])

这打印example

(但是,这在 url 上会失败http://localhost/some/path/to/file.txt


推荐阅读