def getHeadImgs(): #通过二维码登录微信网页版 itchat.auto_login() #获取微信好友信息列表 friendList = itchat.get_friends(update=True) #这里会用到的微信好友信息如下: User= {'UserName': '******','PYQuanPin': 'TED','NickName': 'TED'} #获取用户个人昵称,用于之后文件夹命名、用户头像命名 if friendList[0]['PYQuanPin']: user = friendList[0]['PYQuanPin'] else: user = friendList[0]['NickName'] #先读取用户本人头像,存储名为用户名称 selfHead = "{}/{}.jpg".format(os.getcwd(), user) with open(selfHead, 'wb') as f: head = itchat.get_head_img(friendList[0]['UserName']) f.write(head) #创建文件夹用于存储好友头像 if not os.path.exists(user): os.mkdir(user) #工作路径转到新建文件夹中 os.chdir(user) #获取新建文件夹路径 userspace = os.getcwd() #开始读取好友头像写入新建文件夹中 print("开始读取%d位好友头像..." % (len(friendList) - 1)) for i in range(1, len(friendList)): if i % 100 == 0: print("已读取%d位好友头像,请耐心等待~" % i) try: friendList[i]['head_img'] = itchat.get_head_img( userName=friendList[i]['UserName']) friendList[i][ 'head_img_name'] = "%s.jpg" % friendList[i]['UserName'] except ConnectionError: print('Fail to get %s' % friendList[i]['UserName']) with open(friendList[i]['head_img_name'], 'wb') as f: f.write(friendList[i]['head_img']) print("读取好友头像完毕!") #登出 itchat.logout() #保存头像的文件夹路径和用户本人头像路径返回 return user, selfHead
def get_imgs(): itchat.auto_login(hotReload=True) friends = itchat.get_friends(update=True) # 获取自己的用户信息,返回自己的属性字典 #itchat.search_friends() # 获取特定UserName的用户信息 #itchat.search_friends(userName='******') # 获取任何一项等于name键值的用户 #itchat.search_friends(name='littlecodersh') # 获取分别对应相应键值的用户 itchat.search_friends(wechatAccount='littlecodersh') #下载所有好友的头像图片 num = 0 for friend in friends: img = itchat.get_head_img(userName=friend["UserName"]) #print(userName=friend["UserName"]) save_path = './headImg/' + str(num) + ".png" try: with open(save_path, 'wb') as f: f.write(img) print("正在保存第" + str(num) + "张头像") f.close() except Exception as e: print(e) num += 1
def getFriendsPicture(): pathSave = pathSaveBase + "photo/" itchat.auto_login() friends = itchat.get_friends(update=True)[0:] user = friends[0]["UserName"] num = 0 for i in friends: img = itchat.get_head_img(userName=i["UserName"]) fileImage = open(pathSave + str(num) + ".jpg", 'wb') fileImage.write(img) fileImage.close() num += 1 ls = os.listdir(pathSave) each_size = int(math.sqrt(float(640 * 640) / len(ls))) lines = int(640 / each_size) image = Image.new('RGBA', (640, 640)) x = 0 y = 0 for i in range(0, len(ls) + 1): try: img = Image.open(pathSave + str(i) + ".jpg") except IOError: print("Error") else: img = img.resize((each_size, each_size), Image.ANTIALIAS) image.paste(img, (x * each_size, y * each_size)) x += 1 if x == lines: x = 0 y += 1 image.save(pathSave + 'all.jpg') itchat.send_image(pathSave + "all.jpg", "filehelper")
def getHeadImg(userid):#获取头像 head_img = itchat.get_head_img(userName=userid) imgName = itchat.search_friends(userName=userid)['RemarkName'] if itchat.search_friends(userName=userid)['RemarkName'] != '' else itchat.search_friends(userName=userid)['NickName'] with open('1.jpg','wb')as f: f.write(head_img) itchat.send_image('1.jpg',toUserName=userid) os.remove('1.jpg')
def get_head_image(): """ 获取头像到本地 :return: """ # 获取到所有好友 friends = itchat.get_friends(update=True); print(type(friends)) print(itchat.get_friends()) # 获取到所有好友的个数 friendsNum = len(friends) # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串) # 组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中 for count, f in enumerate(friends): # 保留两位小数,并已 55.57% 的形式打印 print(str(round(count / friendsNum * 100, 2)) + "%") # 根据用户名获取头像 img = itchat.get_head_img(f["UserName"]) if f["RemarkName"] != "": name = f["RemarkName"] else: name = f["NickName"] # 保存头像 fOpen = open("img/" + name + ".jpg", "wb") fOpen.write(img) fOpen.close()
def get_imgs(friends): for num, friend in enumerate(friends): print("friend", friend) img = itchat.get_head_img(userName=friend["UserName"]) fileImg = open("./user/" + str(num) + ".jpg", 'wb') fileImg.write(img) fileImg.close()
def get_wechat(self): try: # 登录微信, hotReload=True:持续登录,无需扫码,手机点击登录即可 # itchat.auto_login(hotReload=True) # 扫码登录 itchat.auto_login() except: print("请检查网络,再重试") # 获取微信好友 friends = itchat.get_friends(update=True) # 创建photo_image文件夹来保存微信头像图片 if not os.path.exists('photo_image'): # 若文件夹不存在,则创建目录 os.mkdir('photo_image') num=0 for friend in friends: # 根据用户名获取对应的微信头像 img=itchat.get_head_img(userName=friend['UserName']) # 图片路径名 img_name=''.join(['photo_image/img',str(num),'.jpg']) # 保存图片 with open(img_name,'wb') as f: f.write(img) num+=1 # 获取生成词云需要的所有好友的个性签名 signature=friend['Signature'].strip() # 剔除个性签名为空以及含span标签的,将所有签名通过空格拼成字符串 if len(signature)>0 and not '<span class=' in signature: self.signature_txt+=signature+' ' self.merge_image() self.merge_love_image() self.draw_heart_shape() self.get_wordcloud()
def get_self_head_img(self, work_dir): head_img = itchat.get_head_img(userName=self.friends[0].UserName) self.head_img_path = os.path.join(work_dir, 'headimg.jpg') with open(self.head_img_path, 'wb') as f: f.write(head_img) return
def head_img(): for count, f in enumerate(itchat.get_friends()): img = itchat.get_head_img(userName=f["UserName"]) imgFile = open("jpg/head_img/" + str(count) + ".jpg", "wb") imgFile.write(img) imgFile.close() print("auto img :%s" % (imgFile))
def get_friends_info(file_name='res/friends_info.txt', download_header=False, save_path='headerImg/'): fh = open(file_name, 'a', encoding='utf8') itchat.login() friends = itchat.get_friends(update=False)[0:] # 设置需要爬取的信息字段 info_k = [ 'NickName', 'RemarkName', 'Sex', 'Province', 'City', 'ContactFlag', 'SnsFlag', 'Signature' ] info_v = ['微信昵称', '备注', '性别', '省份', '城市', '联系标识', '渠道标识', '个性签名'] for v in info_v: fh.write(v + ",") for index, friend in enumerate(friends): print('get ', index) for k in info_k: fh.write( str(friend.get(k)).strip().replace('\n', '').replace('\r', '') + ",") fh.write('\n') if download_header: head = itchat.get_head_img(userName=friend["UserName"]) img_file = open(save_path + str(index) + '.jpg', 'wb') img_file.write(head) img_file.close() print("done")
def save_heads_img(friends_list): '''保存头像数据''' images_dir = './images/' # 判断保存头像的文件夹是否存在,如果不存在则创建 full_path = os.getcwd() + images_dir if not os.path.exists(full_path): os.mkdir(full_path) else: pass print('正在保存好友头像,保存路径为:%s 请稍等' % (os.getcwd() + images_dir)) num = 0 for friend in friends_list: image = itchat.get_head_img(userName=friend['UserName']) # print(image) # 单纯保存为RemarkName.jpg的话,未备注的好友头像文件为 .jpg,有文件覆盖情况 # 另若头像名中包含特殊字符,保存成文件时又会报错,暂时无解? # 另若好友备注名相同的话也会存在文件覆盖情况----文件保存时先判断文件是否存在,如果存在文件名为xxx02.jpg?暂时不实现 # 先按纯数字命名保存头像文件。。。 image_name = str(num) + '.jpg' num += 1 # if friend['RemarkName'] == '': # image_name = friend['NickName']+'.jpg' # else: # image_name = friend['RemarkName']+'.jpg' try: with open(images_dir + image_name, 'wb') as f: f.write(image) except Exception as e: pass print('头像已保存')
def map(chatroomName): num = 0 chatrooms = itchat.get_chatrooms(update=True) for item in chatrooms: print (item["NickName"]) chatrooms = itchat.search_chatrooms(name=chatroomName) if chatrooms is None: print(u'没有找到群聊:' + chatroomName) else: if not os.path.exists("./" + chatroomName): os.mkdir("./" + chatroomName) chatroom = itchat.update_chatroom(chatrooms[0]['UserName']) counter = 0 for friend in chatroom['MemberList']: img = itchat.get_head_img(userName=friend["UserName"],chatroomUserName=chatrooms[0]['UserName']) fileImage = open("./" + chatroomName + "/" + str(counter) + ".jpg", 'wb') counter = counter + 1 try: fileImage.write(img) except: try: print (friend["NickName"] + " error.") except: print (friend["UserName"] + " error.") fileImage.close() num += 1
def get_wechat_profile_photo(save_dir): itchat.auto_login() try: #获取微信好友信息 friendList = itchat.get_friends(update=True) friend_count = len(friendList) print('[+]You have %d friends in all' % (friend_count)) #读取好友头像 photo_count = 0 ProgressPrint(photo_count, 5, friend_count) for friend in friendList: friend['head_img'] = itchat.get_head_img( userName=friend['UserName']) friend['head_img_name'] = "%s\\%d.jpg" % (save_dir, photo_count) #写入文件 with open(friend['head_img_name'], 'wb') as f: f.write(friend['head_img']) photo_count += 1 ProgressPrint(photo_count, 5, friend_count) except: print('[-]Err occured when get friendphotos') itchat.logout()
def download_image(): # 扫描二维码登陆微信,即通过网页版微信登陆 itchat.auto_login() # 返回一个包含用户信息字典的列表 friends = itchat.get_friends(update=True) # 在当前位置创建一个用于存储头像的目录wechatImages base_path = './wechatImages' if not os.path.exists(base_path): os.mkdir(base_path) # 获取所有好友头像 for friend in friends: # 获取头像数据 img_data = itchat.get_head_img(userName=friend['UserName']) #判断备注名是否为空 if friend['RemarkName'] != '': img_name = friend['RemarkName'] else: img_name = friend['NickName'] # 在实际操作中如果文件名中含有*标志,会报错。则直接可以将其替换掉 if img_name is "*": img_name = "" #通过os.path.join()函数来拼接文件名 img_file = os.path.join(base_path, img_name + '.jpg') print(img_file) with open(img_file, 'wb') as file: file.write(img_data)
def downloadFriendsFaces(self): #登录 print("开始登录.....") itchat.auto_login(hotReload=True) #获取好友列表 print("开始获取好友列表.....") friends = itchat.get_friends() #下载好友头像 counter = 0 print("开始下载好友头像.....") for friend in friends: print(".", end="") if (counter + 1) % 60 == 0: print() sys.stdout.flush() username = friend['UserName'] #获取图像并保存 filename = self.facedir + "face%05d.png" % (counter) with open(filename, "wb") as fd: faceData = itchat.get_head_img(userName=username) fd.write(faceData) counter += 1 #下面是为了提高测试速度,正是运行可以注释掉 #if counter>=50: # break print("") print("好友头像下载完毕!")
def text_reply(msg): global OK_FILE global HEAD_FILE # chatroom filter if msg.User["NickName"] != "祖国万岁" and msg.User["NickName"] != "test": return # message filter if msg.text != "祖国万岁": return "@{}\u2005发送任意图片,你会得到加了红旗的头像。请不要发无关的信息,打扰其他人。".format( msg.actualNickName) print(json.dumps(msg)) #itchat.get_head_img(userName=msg["ActualUserName"], picDir = OK_FILE) head = itchat.get_head_img(userName=msg["ActualUserName"]) #return "%s 我们还不是好友,您需要将头像发给我,才能加红旗。".format(msg.actualNickName) if str(type(head)) != "<class 'bytes'>": print(json.dumps(head)) return "@{}\u2005你需要将图片发到群里,才能加红旗。".format(msg.actualNickName) byte_stream = BytesIO(head) headImg = Image.open(byte_stream) pasteFlag.add_flag(img=headImg).save(OK_FILE) itchat.send_image(OK_FILE, toUserName=msg.User["UserName"]) return u'@%s' % (msg.actualNickName)
def getImage(): print("can login in successfully") friends_list = itchat.get_friends() for item in friends_list: # > file 将个性签名重定向到一个文本文件 print(item['Signature']) write_image(item['NickName'],itchat.get_head_img(item['UserName']))
def crawl(self): friends_info_list = itchat.get_friends(update=True) print(friends_info_list[1]) for friend in friends_info_list: print(friend['NickName'], friend['RemarkName'], friend['Sex'], friend['Province'], friend['Signature']) # 处理省份 if friend['Province'] in self.province_dict: self.province_dict[friend['Province']] = self.province_dict[ friend['Province']] + 1 else: if friend['Province'] not in self.province_tuple: if '海外' in self.province_dict.keys(): self.province_dict['海外'] = self.province_dict['海外'] + 1 else: self.province_dict['海外'] = 1 else: self.province_dict[friend['Province']] = 1 self.friends.append(friend) # 保存头像 img = itchat.get_head_img(userName=friend["UserName"]) path = "./pic" if not os.path.exists(path): os.makedirs(path) try: file_name = path + os.sep + friend['NickName'] + "(" + friend[ 'RemarkName'] + ").jpg" with open(file_name, 'wb') as f: f.write(img) except Exception as e: print(repr(e))
def download_headimgs(): for i, f in enumerate(friends): img = itchat.get_head_img( userName=f["UserName"]) # itchat.get_head_img() 获取到头像二进制 imgfile = open("img//" + str(i) + f["RemarkName"] + ".jpg", 'wb') imgfile.write(img) imgfile.close()
def heaImage(): num = 0 for friend in friends: image = itchat.get_head_img( userName=friend["UserName"] ) # 用 itchat.get_head_img(userName=None)来爬取好友列表的头像 fileImage = open("C:/Users/Administrator/Desktop/wechat" + "/" + str(num) + ".jpg", 'wb') # 将好友头像下载到本地文件夹 fileImage.write(image) fileImage.close() num += 1 length = len(os.listdir('C:/Users/Administrator/Desktop/wechat')) each_size = int(math.sqrt(float(810 * 810) / length)) # 每一行可以放多少个 lines = int(810 / each_size) # 生成白色背景新图片 image = Image.new('RGB', (255, 255)) x = 0 y = 0 for i in range(0, length): try: img = Image.open('./headImg/' + str(i) + ".jpg") except IOError: print(i) print("Error") else: img = img.resize((each_size, each_size), Image.ANTIALIAS) # resize image with high-quality image.paste(img, (x * each_size, y * each_size)) x += 1 if x == lines: x = 0 y += 1 image.save('C:/Users/Administrator/Desktop/wechat/ls' + "all.jpg")
def getWechatHeadImg(fName): cacheDir = "static/wechatStuff/{}".format(itchat.myNickName) dirContent = os.listdir(cacheDir) if fName in dirContent: f = open("static/wechatStuff/{}/{}".format(itchat.myNickName, fName), 'rb') content = f.read() f.close() return "data:image/jpeg;base64," + base64.b64encode(content).decode() target=fName[:-4] if " || " in target: remarkName, nickName = target.split(" || ") remarkName = remarkName if remarkName != "" else None pic = itchat.get_head_img(userName=itchat.search_friends(nickName=nickName, remarkName=remarkName)[0]["UserName"]) else: pic = itchat.get_head_img(chatroomUserName=itchat.search_chatrooms(name=target)[0]["UserName"]) return "data:image/jpeg;base64," + base64.b64encode(pic).decode()
def download_images(friends): img_dir = './head_images/' if not os.access(img_dir, os.F_OK) or not os.listdir(img_dir): print('create file in "/head_images/".') for friend in friends: img = itchat.get_head_img(userName=friend['UserName']) with open(img_dir + friend['UserName'] + '.jpg', 'wb') as file: file.write(img)
def getallhead(path): for i in friends: img = itchat.get_head_img(userName=i["UserName"]) try: with open(path + "/" + i["NickName"] + ".png", "wb") as f: f.write(img) except: print('wrong in ', i["NickName"])
def get_header(): num = 0 friends = itchat.get_friends(update=True) for friend in friends: img = itchat.get_head_img(userName=friend['UserName']) with open('D:/spider/wechat/' + str(num) + '.png', 'wb') as f: f.write(img) num += 1
def save_head(name, i): img = itchat.get_head_img(userName=name) print('start saving image') file_name = str(i) + '.jpg' print('start saving file') with open(file_name, 'ab') as f: f.write(img) print(file_name, 'successfully saved')
def down_Img(friends): friends_info = get_friends_info(friends) name_list = friends_info['username'] nick_list = friends_info['nickname'] for i in range(len(name_list)): with open("headImgs/" + str(i) + ".png", "wb") as f: img_dir = itchat.get_head_img(name_list[i]) f.write(img_dir)
def download_images(frined_list): for friend in frined_list: image_name = image_dir + friend['UserName'] + '.jpg' if not os.path.isfile(image_name): print("Downloading head image of %s" % friend['NickName']) img = itchat.get_head_img(userName=friend["UserName"]) with open(image_name, 'wb') as file: file.write(img)
def analyse_headimg(friends): num = 0 use_face = 0 no_use_face = 0 if not os.path.exists('./Resource/headImg'): os.mkdir('./Resource/headImg') print("Downloading headImg......") for i, j in zip(friends, tqdm(range(len(friends)))): img = itchat.get_head_img(i["UserName"]) with open('./Resource/headImg/' + str(num) + ".jpg", 'wb') as f: f.write(img) f.close() num += 1 print("\nDownload completed !\nAnalyzing.....\nPlease wait a few seconds......") # 获取文件夹内的文件个数 length = len(os.listdir('./Resource/headImg')) # 根据总面积求每一个的大小 each_size = int(math.sqrt(float(600 * 600) / length)) # 每一行可以放多少个 lines = int(600 / each_size) # 生成白色背景新图片 image = Image.new('RGBA', (600, 600), 'white') x = 0 y = 0 for i in range(0, length): try: img = Image.open('./Resource/headImg/' + str(i) + ".jpg") img = img.convert("RGB") face_img = cv2.imread('./Resource/headImg/' + str(i) + ".jpg") if detect_face(face_img)==True: use_face += 1 else: no_use_face += 1 except IOError: continue # print(i) # print("Error") else: img = img.resize((each_size, each_size), Image.ANTIALIAS) # 保存图像清晰度 image.paste(img, (x * each_size, y * each_size)) x += 1 if x == lines: x = 0 y += 1 image.show() # 饼状图 labels = ['使用人脸头像','不使用人脸头像'] values = (float(use_face)/length, float(no_use_face)/length) pyplot.pie(values, labels=labels, colors=('red', 'lightskyblue'), labeldistance=1.1, autopct='%2.2f%%', shadow=False, startangle=90, pctdistance=0.6) pyplot.axis('equal') pyplot.title('%s的微信好友使用人脸头像情况' % friends[0]['NickName']) pyplot.legend(loc='upper right') pyplot.grid() pyplot.show()
def get_friend(): # 登录微信 itchat.auto_login(True) # 获取微信所有的好友对象 friends = itchat.get_friends(update=True) parse_friedns(friends) # 获取当前路径 创建pic文件 pic_path = os.getcwd() + '\\pic\\' # 文件夹不存在 则创建 if not os.path.exists(pic_path): os.mkdir(pic_path) file = open('Signature.txt', 'a+', encoding='utf-8') # 性别字典 sex_arr = {} x = 0 for i, friend in enumerate(friends): # 性别 sex = friend['Sex'] if sex == 1: sex_arr['Boy'] = sex_arr.get('Boy', 0) + 1 elif sex == 2: sex_arr['Girl'] = sex_arr.get('Girl', 0) + 1 else: sex_arr['Unknow'] = sex_arr.get('Unknow', 0) + 1 # 替换掉个性签名中的表情等字符..span, emoji signature = friend['Signature'].strip().replace('span', '').replace( 'emoji', '').replace('class', '') rec = re.compile('[^\u4e00-\u9fa5^]') signature = rec.sub("", signature) # 个性签名写入文件 file.write(signature + "\n") # 通过userName 获取头像byte img_byte = itchat.get_head_img(userName=friend['UserName']) uuserName = friend['UserName'].strip().replace('span', '').replace( 'emoji', '').replace('class', '') # img = open(pic_path + str(rec.sub("", uuserName)) + '.jpg', 'wb') img = open(pic_path + str(x) + '.jpg', 'wb') # 图片写入pic文件夹 print('签名', signature) # print(friend['UserName'], uuserName) img.write(img_byte) img.close() x += 1 print('img write end>>>>>>>') # try: # img.write(img_byte) # except OSError as e: # print('OSError:', e) # else: # print('noerro:') # finally: # img.write(img_byte) # img.close() return sex_arr
def download_images(frined_list): image_dir = "./images/" num = 1 for friend in frined_list: image_name = str(num) + '.jpg' num += 1 img = itchat.get_head_img(userName=friend["UserName"]) with open(image_dir + image_name, 'wb') as file: file.write(img)
def download_images(frined_list): image_dir = "./images/" num = 1 for friend in frined_list: image_name = str(num)+'.jpg' num+=1 img = itchat.get_head_img(userName=friend["UserName"]) with open(image_dir+image_name, 'wb') as file: file.write(img)
def headImg(): itchat.login() friends = itchat.get_friends(update=True) # itchat.get_head_img() 获取到头像二进制,并写入文件,保存每张头像 for count, f in enumerate(friends): # 根据userName获取头像 img = itchat.get_head_img(userName=f["UserName"]) imgFile = open("img/" + str(count) + ".jpg", "wb") imgFile.write(img) imgFile.close()
itchat.auto_login() friends = itchat.get_friends(update=True)[0:] user = friends[0]["UserName"] full_path = f'F:\{user}' if not os.path.exists(full_path): os.mkdir(full_path) # 为自己创建一个文件夹 os.chdir(full_path) # 切换路径 num = 0 for i in friends: img = itchat.get_head_img(userName=i["UserName"]) with open(str(num) + ".jpg", 'wb') as f: f.write(img) num += 1 pics = listdir('.') numPic = len(pics) print(numPic) eachsize = int(math.sqrt(float(640 * 640) / numPic)) print(eachsize) numline = int(640 / eachsize)