Python code to determine if TLD exists, prompt again if not?

房东的猫 提交于 2019-12-24 10:55:34

问题


This is an additional question in regards to this post: Python raw_input with forced TLD?

I have a check in place to see if a string ends with a TLD,

TLD = ('.com', '.info', '.org', '.net')
if raw_input("Please enter a hostname").endswith(TLD):
# blah blah

But I am attempting to store the raw_input in to a variable. Would the proper coding practice be to do something such as:

TLD = ('.com', '.info', '.org', '.net')
hostName = raw_input(":").lower()
<<piece of code that determines if hostName does in fact end with a TLD?>>

If so, what would that look like? I attempted a while True: and an if elif statement but I am not getting anywhere, I have googled endlessly with no results which is why I post this question here.

The program in question will grab the hostname, say google.com, determine if it has a valid TLD, strip the TLD off of hostName and store it in hostNameshort (both will be used later), if it doesn't get a proper TLD prompt again with emphasis on that it needs the TLD during input time, and then continue on once it does.


回答1:


Something like this:

TLD = ('.com', '.info', '.org', '.net')
hostName = raw_input(":").lower()
while not hostName.endswith(TLD):
    print "Incorrect input, Try again!"
    hostName = raw_input(":").lower()

Demo:

:foo.bar
Incorrect input, Try again!
:google.in
Incorrect input, Try again!
:yahoo.com



回答2:


Actual DNS lookup to test a TLD

Ohh, while we are at it, maybe a short snippet to actually test TLD's against the DNS servers might become handy. I'm using the dnspython module from the Nominum guys:

import dns.resolver

def testTLD(tld):
    try:
        dns.resolver.query(tld + '.', 'SOA')
        return True
    except dns.resolver.NXDOMAIN:
        return False

for tld in ('com', 'org', 'klonk', 'dk'):
    print "TLD \"{tld}\" exists: {bool}".format(tld=tld, bool=testTLD(tld))

and it runs like this:

TLD "com" exists: True
TLD "org" exists: True
TLD "klonk" exists: False
TLD "dk" exists: True


来源:https://stackoverflow.com/questions/16822171/python-code-to-determine-if-tld-exists-prompt-again-if-not

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