gethostbyname和hasattr, getattr, setattr函数的使用

本文介绍使用Python中的gethostbyname函数来获取URL中域名对应的IP地址的方法,并对比两种不同的实现方式。此外,还介绍了Python中hasattr(), getattr(), setattr()等函数的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gethostbyname 函数

  • 功能:获取url 的域名的 IP,而不是整个URL的 IP
from socket import gethostbyname
url = "https://www.crifan.com/python_re_sub_detailed_introduction/"
# 获取的是域名的 IP,不是整个URL的 IP
print gethostbyname('www.crifan.com')
print gethostbyname('www.baidu.com')

def dns_check(url):
    '''
    探测URL的IP
    '''
    if url.find("//") != -1:
        print url
        print url.find("//")
        url = url[url.find("//") + 2:]
        print url
    if url[-1] == '/':
        url = url[:-1]
        print url
    try:
        ip = gethostbyname(url)
    except Exception,e:
        print e

        ip = ''
    return ip

print dns_check(url)
#---------------------------------------------------输出
107.151.176.131
61.135.169.125
https://www.crifan.com/python_re_sub_detailed_introduction/
6
www.crifan.com/python_re_sub_detailed_introduction/
www.crifan.com/python_re_sub_detailed_introduction
[Errno 11001] getaddrinfo failed

##################################################################### 另外一种方法
from urlparse import urlparse
url = "https://www.crifan.com/python_re_sub_detailed_introduction/"
parts = urlparse(url)
host = parts.netloc
print host
print gethostbyname(host)
# -------------------------------------------------------------输出
www.crifan.com
107.151.176.131

hasattr() , getattr(), setattr() 函数

  • hasattr(object, name) : 判断一个对象里面是否有 name 属性或者 name方法,返回BOOL值,有name特性返回True, 否则返回False。
  • getattr(object,name) : 获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。
  • setattr(object,name) :给对象的属性赋值,若属性不存在,先创建再赋值。
class test():
    name="xiaohua"
    def run(self):
        return "HelloWord"
t = test()
#判断对象有name属性
print hasattr(t,"name")
print hasattr(t,"run")
# 获取对象属性值
print getattr(t,'name')
print getattr(t,'run')
# 设置对象属性值
if not hasattr(t,'age'):
    setattr(t,'age',18)
    print getattr(t,'age')
# -----------------------------------输出
True
True
xiaohua
<bound method test.run of <__main__.test instance at 0x0000000002A64888>>
18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值