如何用Python编写工具来查询并获取当前设备的IP地址?
- 内容介绍
- 文章标签
- 相关推荐
本文共计525个文字,预计阅读时间需要3分钟。
python获取IP地址并判断其有效性import requestsfrom lxml import etreeimport time
headers={ User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)}
def get_ip_address(): url=http://api.ip.cn/ response=requests.get(url, headers=headers) time.sleep(1) # 避免频繁请求
if response.status_code==200: ip_info=response.text print(ip_info) tree=etree.HTML(ip_info) ip=tree.xpath('//div[@id=ip]/text()')[0] print(当前IP:, ip)
if 无效 not in ip_info: print(地址有效,保存成功。) # 保存IP地址 with open(valid_ip.txt, w) as file: file.write(ip) else: print(地址无效。) else: print(请求失败。)
get_ip_address()
一、获取IP地址
二、判断地址是否可用。并把可的地址保存。
本文共计525个文字,预计阅读时间需要3分钟。
python获取IP地址并判断其有效性import requestsfrom lxml import etreeimport time
headers={ User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)}
def get_ip_address(): url=http://api.ip.cn/ response=requests.get(url, headers=headers) time.sleep(1) # 避免频繁请求
if response.status_code==200: ip_info=response.text print(ip_info) tree=etree.HTML(ip_info) ip=tree.xpath('//div[@id=ip]/text()')[0] print(当前IP:, ip)
if 无效 not in ip_info: print(地址有效,保存成功。) # 保存IP地址 with open(valid_ip.txt, w) as file: file.write(ip) else: print(地址无效。) else: print(请求失败。)
get_ip_address()
一、获取IP地址
二、判断地址是否可用。并把可的地址保存。

