Python获取url中域名及从域名中提取ip的方法

Python039

Python获取url中域名及从域名中提取ip的方法,第1张

这种方法为从urlparse模块中通过urlparse方法提取url通过hostname属性获取当前url的域名

此方法是通过urllib模块中splittype方法先从url中获取到proto协议及rest结果,然后通过splithost从rest中获取到host及rest结果,此时host为域名。(rest被分割了两次)如下图:

此方法为从sokcet模块中获取到gethostbyname方法将域名传递进去就能解析出域名的ip。

此方法为通过nslookup获取域名的ip。

以上从域名中提取ip会不准确,需要设置DNS服务器,这样解析域名就准确了。

使方法一、用IP138数据库查询域名或IP地址对应的地理位置。

?

1234567891011121314151617181920212223242526

#-*- coding:gbk -*-import urllib2import re try: while True: ipaddr = raw_input("Enter IP Or Domain Name:") if ipaddr == "" or ipaddr == 'exit': break else: url = "http://www.ip138.com/ips138.asp?ip=%s&action=2" % ipaddr u = urllib2.urlopen(url) s = u.read() #Get IP Address ip = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',s) print "\n****** Below Result From IP138 Database *****" print "IP Address:",ip[0] #Get IP Address Location result = re.findall(r'(<li>.*?</li>)',s) for i in result:print i[4:-5] print "*"*45 print "\n" except: print "Not Data Find"

方法二、本来想调用阿里的ip接口查询ip归属地。结果发现阿里的接口非常不给力,主要是不准确,不过是免费的且有地区和ISP的信息。以下是实现代码