下面就详细跟大家分享一些Python的骚操作:

1、Python让你不再错过抢红包

刚过完年经历了抢红包大战的大家,是不是错过了好几个亿!?

用黑科技Python,开发一个微信小助手,从此再也不用担心错过巨额红包啦!

实现代码主要有两个部分:

(1)接收红包消息,直接从手机端微信获取数据比较麻烦,主流的方法都是通过微信网页版来获取。

因为网页版的消息接口可以被抓包分析,比较容易获取和使用。

(2)发通知,最简单的通知方法就是发出声音,还嫌不够的话,可以弹个窗。

# 打开手机微信 poco(text='微信').click() #获取当前页面中所有所有群聊的名称  群聊消息的元素标识Chat_msg = poco(name='com.tencent.mm:id/d1v').offspring('com.tencent.mm:id/b6e') # 获取当前页面中所有群聊的名称 Chat_names = [] Chat_names = list(map(lambda x: x.get_text(), Chat_msg)) # 指定抢红包的群聊名称 chat = input('请指定群聊名称:') if chat in Chat_names:  index = Chat_names.index(chat)  # 点击进入指定的群聊  Chat_msg[index].click() 在微信聊天页面中,获取当前页面中的所有消息元素。 msg_list = poco("android.widget.ListView").children() #   遍历消息并查找红包 for msg in msg_list: # 微信红包的标识  LuckyMoney = msg.offspring('com.tencent.mm:id/aql')  # 已失效红包(比如已领取、已被领完)的标识  Invalid = msg.offspring('com.tencent.mm:id/aqk')  # 判断红包是否有效并抢起来!  if LuckyMoney:  pass     #遍历消息并查找红包 if Invalid.exists() and (Invalid.get_text()=='已领取' or Invalid.get_text()=='已被领完'): print(f'红包已无效,跳过……') continueelse:  print(f'发现一个新红包,抢起来!')  poco("com.tencent.mm:id/d1v")  msg.click()  click_open = poco("com.tencent.mm:id/d02")  if click_open.exists():  click_open.click()  keyevent('BACK') #初始化程序 from airtest.core.api import * auto_setup(__file__) from poco.drivers.android.uiautomation import AndroidUiautomationPoco poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)

2、Python帮你抢火车票

Python除了抢红包,也是抢火车票的一把好手,说不定你当年买下的黄牛贩子手里的票就是靠Python抢到的。

大家过年回家抢票是不是巨艰辛,今年过年可以写个抢票软件啦!

使用 Python3 抓取12306网站的 车票信息,及时提醒,自动下单。

from splinter.browser import Browser from time import sleep import traceback class Buy_Tickets(object):     # 定义实例属性,初始化     def __init__(self, username, passwd, order, passengers, dtime, starts, ends):         self.username = username         self.passwd = passwd         # 车次,0代表所有车次,依次从上到下,1代表所有车次,依次类推         self.order = order         # 乘客名         self.passengers = passengers         # 起始地和终点         self.starts = starts         self.ends = ends         # 日期         self.dtime = dtime         # self.xb = xb         # self.pz = pz         self.login_url = 'https://kyfw.12306.cn/otn/login/init'         self.initMy_url = 'https://kyfw.12306.cn/otn/index/initMy12306'         self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init'         self.driver_name = 'chrome'         self.executable_path = 'C:Python36Scriptschromedriver.exe'     # 登录功能实现     def login(self):         self.driver.visit(self.login_url)         self.driver.fill('loginUserDTO.user_name', self.username)         # sleep(1)         self.driver.fill('userDTO.password', self.passwd)         # sleep(1)         print('请输入验证码...')         while True:             if self.driver.url != self.initMy_url:                 sleep(1)             else:                 break     # 买票功能实现     def start_buy(self):         self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)         #窗口大小的操作         self.driver.driver.set_window_size(700, 500)         self.login()         self.driver.visit(self.ticket_url)         try:             print('开始购票...')             # 加载查询信息             self.driver.cookies.add({"_jc_save_fromStation": self.starts})             self.driver.cookies.add({"_jc_save_toStation": self.ends})             self.driver.cookies.add({"_jc_save_fromDate": self.dtime})             self.driver.reload()             count = 0             if self.order != 0:                 while self.driver.url == self.ticket_url:                     self.driver.find_by_text('查询').click()                     count += 1                     print('第%d次点击查询...' % count)                     try:                         self.driver.find_by_text('预订')[self.order-1].click()                         sleep(1.5)                     except Exception as e:                         print(e)                         print('预订失败...') continue            else:                 while self.driver.url == self.ticket_url:                     self.driver.find_by_text('查询').click()                     count += 1                     print('第%d次点击查询...' % count)                     try:                         for i in self.driver.find_by_text('预订'):                             i.click()                             sleep(1)                     except Exception as e:                         print(e)                         print('预订失败...') continue            print('开始预订...')             sleep(1)             print('开始选择用户...')             for p in self.passengers:                 self.driver.find_by_text(p).last.click()                 sleep(0.5)                 if p[-1] == ')':                     self.driver.find_by_id('dialog_xsertcj_ok').click()             print('提交订单...')             # sleep(1)             # self.driver.find_by_text(self.pz).click()             # sleep(1)             # self.driver.find_by_text(self.xb).click()             # sleep(1)             self.driver.find_by_id('submitOrder_id').click()             sleep(2)             print('确认选座...')             self.driver.find_by_id('qr_submit_id').click()             print('预订成功...')         except Exception as e:             print(e) if __name__ == '__main__':     # 用户名     username = 'xxxx'     # 密码     password = 'xxx'     # 车次选择,0代表所有车次     order = 2     # 乘客名,比如passengers = ['丁小红', '丁小明']     # 学生票需注明,注明方式为:passengers = ['丁小红(学生)', '丁小明']     passengers = ['丁彦军']     # 日期,格式为:'2018-01-20'     dtime = '2018-01-19'     # 出发地(需填写cookie值)     starts = '%u5434%u5821%2CWUY' #吴堡     # 目的地(需填写cookie值)     ends = '%u897F%u5B89%2CXAY' #西安     # xb =['硬座座']      # pz=['成人票']     Buy_Tickets(username, password, order, passengers, dtime, starts, ends).start_buy()

3、Python帮你选房子

过完年很多朋友要开始租房,自己一个个晒一个个查看是不是太累?

那就写个Python脚本吧,爬取某租房网站的房源信息,利用高德的 js API 在地图上标出房源地点,划出距离工作地点1小时内可到达的范围。

对比租金等,轻轻松松选出最适合的房子。




python 自动打开网页地址 python自动点击网页链接_微信


代码

链家的房租网站 两个导入的包 1.requests 用来过去网页内容 2.BeautifulSoup import time import pymssql import requests from bs4 import BeautifulSoup # https://wh.lianjia.com/zufang/ #获取url中下面的内容 def get_page(url): responce = requests.get(url) soup = BeautifulSoup(responce.text,'lxml') return soup #封装成函数,作用是获取列表下的所有租房页面的链接,返回一个链接列表 def get_links(url): responce = requests.get(url) soup = BeautifulSoup(responce.text,'lxml') link_div = soup.find_all('div',class_ = 'pic-panel') links = [div.a.get('href') for div in link_div] return links #收集一个房子的信息 def get_house_info(house_url): soup = get_page(house_url) price = soup.find('span',class_='total').text unit = soup.find('span',class_= 'unit').text[1:-1] area = soup.find('p', class_ = 'lf').text house_info= soup.find_all('p',class_ = 'lf') area = house_info[0].text[3:] #字符串切片工具 layout = house_info[1].text[5:] info={ '价格':price, '单位':unit, '面积':area, '户型':layout } return info #链接数据库 server="192.168.xx.xx" #换成自己的服务器信息 user="liujiepeng" password="xxxxx" #自己的数据库用户名和密码 conn=pymssql.connect(server,user,password,database="house") def insert(conn,house): #sql_values = values.format(house['价格'],house['单位'],house['面积'], #house['户型']) sql = "insert into [house].dbo.lianjia(price,unit,area,layout)values('%s','%s','%s','%s')"%(house["价格"],house["单位"],house["面积"],house["户型"]) print(sql) cursor = conn.cursor() #游标,开拓新的窗口 #cursor1 = conn.cursor() cursor.execute(sql) #执行sql语句 conn.commit() #提交 ,更新sql 语句 links = get_links('https://wh.lianjia.com/zufang/') count = 1 for link in links: #time.sleep(2) print('获取一个数据成功') house = get_house_info(link) insert(conn,house) print("第%s个数据,存入数据库成功!"%(count)) count = count+1 #print(house["价格"],end='')

4、Python找回女神撤回的消息

除了这些日常操作,麦教授说几个你想不到的吧。

当自己一直喜欢的女神发给自己一个消息的时候,还没来得及看,就撤回了。

是不是自己在心中"YY",她是不是发了什么,然后你问她的时候,她却说没什么。

学会Python,你可以做一个程序,把私聊撤回的信息可以收集起来并发送到个人微信的文件传输助手。


python 自动打开网页地址 python自动点击网页链接_微信_02


5、Python自己写小游戏

用Python写几个小游戏玩玩也不过是几十行代码的事,比如写个贪吃蛇!

还记得之前火爆一时的跳一跳,如果你早点学会Python,就可以常年占据排行榜第1了,还是全自动的效果,很有趣!

跳一跳代码:

from __future__ import print_function import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import math import time import os import cv2 import datetime scale = 0.25 template = cv2.imread('character.png') template = cv2.resize(template, (0, 0), fx=scale, fy=scale) template_size = template.shape[:2] def search(img):  result = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)  min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)  cv2.rectangle(img, (min_loc[0], min_loc[1]), (min_loc[0] + template_size[1], min_loc[1] + template_size[0]), (255, 0, 0), 4)  return img, min_loc[0] + template_size[1] / 2, min_loc[1] + template_size[0] def pull_screenshot():  filename = datetime.datetime.now().strftime("%H%M%S") + '.png'  os.system('mv autojump.png {}'.format(filename))  os.system('adb shell screencap -p /sdcard/autojump.png')  os.system('adb pull /sdcard/autojump.png .') def jump(distance):  press_time = distance * 1.35  press_time = int(press_time)  cmd = 'adb shell input swipe 320 410 320 410 ' + str(press_time)  print(cmd)  os.system(cmd) def update_data():  global src_x, src_y  img = cv2.imread('autojump.png')  img = cv2.resize(img, (0, 0), fx=scale, fy=scale)  img, src_x, src_y = search(img)  return img fig = plt.figure() index = 0 # pull_screenshot() img = update_data() update = True  im = plt.imshow(img, animated=True) def updatefig(*args):  global update  if update:  time.sleep(1)  pull_screenshot()  im.set_array(update_data())  update = False  return im, def onClick(event):   global update   global src_x, src_y  dst_x, dst_y = event.xdata, event.ydata  distance = (dst_x - src_x)**2 + (dst_y - src_y)**2   distance = (distance ** 0.5) / scale  print('distance = ', distance)  jump(distance)  update = True fig.canvas.mpl_connect('button_press_event', onClick) ani = animation.FuncAnimation(fig, updatefig, interval=5, blit=True) plt.show()

贪吃蛇代码:

#!/usr/bin/env python import pygame,sys,time,random from pygame.locals import * # 定义颜色变量 redColour = pygame.Color(255,0,0) blackColour = pygame.Color(0,0,0) whiteColour = pygame.Color(255,255,255) greyColour = pygame.Color(150,150,150) # 定义gameOver函数 def gameOver(playSurface):  gameOverFont = pygame.font.Font('arial.ttf',72)  gameOverSurf = gameOverFont.render('Game Over', True, greyColour)  gameOverRect = gameOverSurf.get_rect()  gameOverRect.midtop = (320, 10)  playSurface.blit(gameOverSurf, gameOverRect)  pygame.display.flip()  time.sleep(5)  pygame.quit()  sys.exit() # 定义main函数 def main():  # 初始化pygame  pygame.init()  fpsClock = pygame.time.Clock()  # 创建pygame显示层  playSurface = pygame.display.set_mode((640,480))  pygame.display.set_caption('Raspberry Snake')  # 初始化变量  snakePosition = [100,100]  snakeSegments = [[100,100],[80,100],[60,100]]  raspberryPosition = [300,300]  raspberrySpawned = 1  direction = 'right'  changeDirection = direction  while True:  # 检测例如按键等pygame事件  for event in pygame.event.get():  if event.type == QUIT:  pygame.quit()  sys.exit()  elif event.type == KEYDOWN:  # 判断键盘事件  if event.key == K_RIGHT or event.key == ord('d'):  changeDirection = 'right'  if event.key == K_LEFT or event.key == ord('a'):  changeDirection = 'left'  if event.key == K_UP or event.key == ord('w'):  changeDirection = 'up'  if event.key == K_DOWN or event.key == ord('s'):  changeDirection = 'down'  if event.key == K_ESCAPE:  pygame.event.post(pygame.event.Event(QUIT))  # 判断是否输入了反方向  if changeDirection == 'right' and not direction == 'left':  direction = changeDirection  if changeDirection == 'left' and not direction == 'right':  direction = changeDirection  if changeDirection == 'up' and not direction == 'down':  direction = changeDirection  if changeDirection == 'down' and not direction == 'up':  direction = changeDirection  # 根据方向移动蛇头的坐标  if direction == 'right':  snakePosition[0] += 20  if direction == 'left':  snakePosition[0] -= 20  if direction == 'up':  snakePosition[1] -= 20  if direction == 'down':  snakePosition[1] += 20  # 增加蛇的长度  snakeSegments.insert(0,list(snakePosition))  # 判断是否吃掉了树莓  if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:  raspberrySpawned = 0  else:  snakeSegments.pop()  # 如果吃掉树莓,则重新生成树莓  if raspberrySpawned == 0:  x = random.randrange(1,32)  y = random.randrange(1,24)  raspberryPosition = [int(x*20),int(y*20)]  raspberrySpawned = 1  # 绘制pygame显示层  playSurface.fill(blackColour)  for position in snakeSegments:  pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))  pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1],20,20))  # 刷新pygame显示层  pygame.display.flip()  # 判断是否死亡  if snakePosition[0] > 620 or snakePosition[0]  460 or snakePosition[1]