简体   繁体   English

如何从Python中的给定URL中提取主机名?

[英]How to extract hostname from the given URL in Python?

How can I extract the hostname from: hostname:/file_name ? 如何从hostname:/file_name提取主机hostname:/file_name For example in ngs.pradhi.com:/upload , I want to extract ngs.pradhi.com from it and test it via ssh.connect. 例如在ngs.pradhi.com:/upload ,我想从中提取ngs.pradhi.com并通过ssh.connect进行测试。

How can I do that? 我怎样才能做到这一点?

The string in your example isn't a URL, so you won't be able to use the standard URL module ( urlparse ) to parse it. 示例中的字符串不是URL,因此您将无法使用标准URL模块( urlparse )来解析它。 Here is how you can do it by hand: 以下是您可以手动完成的方法:

In [43]: path = 'ngs.pradhi.com:/upload'

In [44]: path.split(':')[0]
Out[44]: 'ngs.pradhi.com'

For SSH, take a look at paramiko . 对于SSH,请查看paramiko

You should consider using the urlparse module: 您应该考虑使用urlparse模块:

This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.” 该模块定义了一个标准接口,用于在组件中解析统一资源定位符(URL)字符串(寻址方案,网络位置,路径等),将组件组合回URL字符串,并将“相对URL”转换为绝对URL给出“基本URL”。

Example: 例:

>>> import urlparse
>>> urlparse.urlparse('http://ngs.pradhi.com/upload')
ParseResult(scheme='http', netloc='ngs.pradhi.com', path='/upload', params='', query='', fragment='')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM