Python working with hostnames, hostname to IP

只谈情不闲聊 提交于 2021-02-05 09:28:27

问题


In python I need to get IP from hostname:

socket.gethostbyname('www.python.org') # returns ip good
socket.gethostbyname('http://python.org') # raises error

I need to deal with hostnames starting with 'http://' so I figured out a way to remake them like this:

a = 'http://python.org'
a.replace('http://', 'www.')
print a # Why does it print http://python.org ???

I'm not sure I do the right thing. Plz help me with translating this type of hostname to IP


回答1:


You want urlparse:

>>> import urlparse
>>> urlparse.urlparse('http://python.org')
ParseResult(scheme='http', netloc='python.org', path='', params='', query='', fragment='')
>>> urlparse.urlparse('http://python.org').netloc
'python.org'
>>> 

Oh, and yes, you don't need to add any "www" in front of the top-level domain.




回答2:


You should do it like this,

a = 'http://python.org'
a = a.replace('http://', 'www.')  
# a.replace() does not change the original string. it returns a new string (replaced version).
print a



回答3:


You have several problems.

1st. Error is raised, because http://stuff is not a valid domain. It is natural to expect an error.

2nd. b does not exists in the context you provided.

3rd. It is a dangerous thing to swap http:// for www. blindly. python.org and www.python.org are two different domains and they may point to different places!

You should use regular expressions or some other routines to extract the domain name from an URL, and use gethostbyname on it.



来源:https://stackoverflow.com/questions/20880285/python-working-with-hostnames-hostname-to-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!