Python Tkinter+爬虫实现ip定位程序

使用tkinter创建查询GUI窗口, 接收ip或域名输入并发送到ip查询网www.ipip.net, 利用正则表达式从返回信息中提取出所需信息并显示在GUI窗口中

环境: python3.6.4


import tkinter
import requests
import re


# 查询函数, 接收用户输入的ip地址
def find_position():

    # 获取输入信息
    ip = ip_input.get()

    # 向ip查询网址发送post请求并获取返回数据
    r = requests.get('https://www.ipip.net/ip/{}.html'.format(ip)).text

    # 正则表达式
    address = re.search(r'地理位置.*?;">(.*?)</span>', r, re.S)
    operator = re.search(r'运营商.*?;">(.*?)</span>', r, re.S)
    time = re.search(r'时区.*?;">(.*?)</span>', r, re.S)
    wrap = re.search(r'地区中心经纬度.*?;">(.*?)</span>', r, re.S)

    # 判断是否匹配成功
    if address:

        # 匹配成功则一定有ip和地理位置信息
        ip_info = ['地理位置:   ' + address.group(1), '当前IP:   ' + ip]

        # 分别判断其他信息匹配结果, 成功则加入临时列表
        if operator:
            ip_info.insert(0, '所有者/运营商:   ' + operator.group(1))
        if time:
            ip_info.insert(0, '时区:   ' + time.group(1))
        if wrap:
            ip_info.insert(0, '地区中心经纬度:   ' + wrap.group(1))

        # 清空之前的回显列表
        display_info.delete(0, 5)

        # 为回显列表赋值
        for item in ip_info:
            display_info.insert(0, item)
    else:
        display_info.delete(0, 5)
        display_info.insert(0, "无效的ip!")


# 创建主窗口
root = tkinter.Tk()
# 设置标题内容
root.title("ip定位")
# 创建输入框并设置尺寸
ip_input = tkinter.Entry(root, width=40)
# 创建一个回显列表
display_info = tkinter.Listbox(root, width=60, height=10)
# 创建查询按钮
result_button = tkinter.Button(root, command=find_position, text="查询")


def main():
    # 完成布局
    ip_input.pack()
    display_info.pack()
    result_button.pack()
    tkinter.mainloop()


if __name__ == '__main__':
    main()

运行结果:
查询结果

猜你喜欢

转载自blog.csdn.net/zzh2910/article/details/81318470