问题
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