使用urlspli仅从url获取域名

2024-04-23 23:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含不同形式URL的数据集(例如https://stackoverflow.com, https://www.stackoverflow.com, stackoverflow.com),我只需要像stackoverflow这样的域名。你知道吗

我使用了来自urllibparse.urlsplit(url),但在我的案例中效果不佳。你知道吗

我怎么才能只得到域名?你知道吗

编辑:

我的代码:

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/, , )

Tags: 数据httpscomurldfparsewwwurllib
3条回答

新的答案,为网址和主机名也工作

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

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。你知道吗

旧答案,仅适用于URL

您可以使用urlspit返回的netloc值,另外还可以进行一些额外的裁剪以获得所需的域(部分):

from urllib.parse import urlsplit

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

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

它打印example。你知道吗

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

您可以使用正则表达式(regex)执行此任务。你知道吗

import re

URL = "https://www.test.com"
result = re.search("https?:\/\/(www.)?([\w\.\_]+)", URL)
print(result.group(2))

# output: test.com

处理此类问题的最佳方法是使用regex。你知道吗

相关问题 更多 >