我需要从cmd窗口爬取很多数据,举一个简单的例子,我想同过cmd中‘ipconfig’指令,把其中IPv4的的地址print出来
import os, re
result = os.popen('ipconfig')
IPv4 = re.findall("(?<=IPv4 地址 . . . . . . . . . . . . : ).*$", result.read())
print(IPv4)
运行结果为[]
当我把result.read()直接替换成 'IPv4 地址 . . . . . . . . . . . . : 192.168.11.6'后,就可以print出['192.168.11.6'],应该来说我的正则表达式是没有问题的
import os, re
result = os.popen('ipconfig')
IPv4 = re.findall('(?<=IPv4 地址 . . . . . . . . . . . . : ).*$', 'IPv4 地址 . . . . . . . . . . . . : 192.168.11.6')
print(IPv4)
现在不清楚问题到底出在哪里了,或者什么其他更好的方式。我需要从cmd窗口里获取很多数据,以上只是一个好理解的举例,我知道python获取IPv4有很多方法。万分感谢
IPv4 = re.findall('(?<=IPv4 地址 . . . . . . . . . . . . : ).*', result.read())
import re, os
def get_ipconfig_ip():
match_ip_dict = {}
ipconfig_result_list = os.popen('ipconfig').readlines() #执行cmd命令ipconfig,并将结果存于ipconfig_result_list
for i in range(0, len(ipconfig_result_list)): #逐行查找
if re.search(r'IPv4 地址' , ipconfig_result_list[i] ) != None:
match_ip = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ipconfig_result_list[i]).group(0) #由正则表达式获取ip地址
for j in range(3,7):
if re.search(r"适配器" , ipconfig_result_list[i - j] ) != None:
match_ip_dict[ipconfig_result_list[i - j]] = match_ip
return match_ip_dict
if __name__ == '__main__': #主程序入口
ip_dict = get_ipconfig_ip() #返回字典ip_dict保存ip地址信息
for i in ip_dict:
print('{} {}'.format(i[0:-1], ip_dict[i])) #字符串format函数,其中i[0:-1]除去键的最后'\n'
把正则最后的$去掉,或者用多行匹配模式
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!