python - 使用 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/, , )
解决方案
新答案,也适用于网址和主机名
要处理没有协议定义的实例(例如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
这在所有情况下都会打印。
旧答案,仅适用于网址
您可以使用netloc
urlsplit 返回的值,另外通过一些额外的定制来获得您想要的域(部分):
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
)
推荐阅读
- git - Git 终端语言在“git checkout”后更改为另一个分支
- php - WooCommerce 自动分配产品类别和产品状态
- r - 恢复图形参数时的警告
- python - 解析财务报表时无法解决字典更新值错误
- python - 如何通过 Selenium 和 Python 向 Instagram 中的用户名和密码字段发送文本
- python-3.x - Python 3 Tkinter 按钮命令不起作用(非常具体的场景)
- kotlin - 具有 Kotlin 依赖项的 OSGi 项目
- javascript - 如何在多个标签中使用类名添加 ID?
- swift - 状态栏中的自定义视图未在辅助屏幕上显示为禁用
- javascript - 使用js生成时出现div的文本