有人說榕栏,“Python除了不會生孩子,Python從撩妹到裝x蕾各,無所不能臼膏!什么都會!”
下載視頻示损?我用Python渗磅;
玩跳一跳?我用Python跳到4999分检访;
撩妹子始鱼?依然用Python;
搶紅包搶火車票脆贵?沒錯還是Python医清;
就算是整理文件,我也還是用Python……
下面就詳細(xì)跟大家分享一些Python的騷操作:
1卖氨、Python讓你不再錯過搶紅包
剛過完年經(jīng)歷了搶紅包大戰(zhàn)的大家会烙,是不是錯過了好幾個億!筒捺?
用黑科技Python柏腻,開發(fā)一個微信小助手,從此再也不用擔(dān)心錯過巨額紅包啦系吭!
實(shí)現(xiàn)代碼主要有兩個部分:
1五嫂、接收紅包消息,直接從手機(jī)端微信獲取數(shù)據(jù)比較麻煩肯尺,主流的方法都是通過微信網(wǎng)頁版來獲取沃缘。
因?yàn)榫W(wǎng)頁版的消息接口可以被抓包分析,比較容易獲取和使用则吟。
2槐臀、發(fā)通知,最簡單的通知方法就是發(fā)出聲音氓仲,還嫌不夠的話水慨,可以彈個窗败匹。
# 打開手機(jī)微信
poco(text='微信').click()
#獲取當(dāng)前頁面中所有所有群聊的名稱
群聊消息的元素標(biāo)識Chat_msg = poco(name='com.tencent.mm:id/d1v').offspring('com.tencent.mm:id/b6e')
# 獲取當(dāng)前頁面中所有群聊的名稱
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)
?# 點(diǎn)擊進(jìn)入指定的群聊
?Chat_msg[index].click()
在微信聊天頁面中,獲取當(dāng)前頁面中的所有消息元素讥巡。
msg_list = poco("android.widget.ListView").children()
# 遍歷消息并查找紅包
for msg in msg_list:
# 微信紅包的標(biāo)識
?LuckyMoney = msg.offspring('com.tencent.mm:id/aql')
?# 已失效紅包(比如已領(lǐng)取掀亩、已被領(lǐng)完)的標(biāo)識
?Invalid = msg.offspring('com.tencent.mm:id/aqk')
?# 判斷紅包是否有效并搶起來!
?if LuckyMoney:
?pass
#遍歷消息并查找紅包
if Invalid.exists() and (Invalid.get_text()=='已領(lǐng)取' or Invalid.get_text()=='已被領(lǐng)完'):
print(f'紅包已無效欢顷,跳過……')
?continue
else:
?print(f'發(fā)現(xiàn)一個新紅包槽棍,搶起來!')
?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除了搶紅包炼七,也是搶火車票的一把好手,說不定你當(dāng)年買下的黃牛販子手里的票就是靠Python搶到的布持。
大家過年回家搶票是不是巨艱辛豌拙,今年過年可以寫個搶票軟件啦!
使用?Python3 抓取12306網(wǎng)站的 車票信息题暖,及時提醒按傅,自動下單。
from splinter.browser import Browser
from time import sleep
import traceback
class Buy_Tickets(object):
????# 定義實(shí)例屬性胧卤,初始化
????def __init__(self, username, passwd, order, passengers, dtime, starts, ends):
????????self.username = username
????????self.passwd = passwd
????????# 車次唯绍,0代表所有車次,依次從上到下枝誊,1代表所有車次况芒,依次類推
????????self.order = order
????????# 乘客名
????????self.passengers = passengers
????????# 起始地和終點(diǎn)
????????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:\Python36\Scripts\chromedriver.exe'
????# 登錄功能實(shí)現(xiàn)
????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('請輸入驗(yàn)證碼...')
????????while True:
????????????if self.driver.url != self.initMy_url:
????????????????sleep(1)
????????????else:
????????????????break
????# 買票功能實(shí)現(xiàn)
????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次點(diǎn)擊查詢...' % count)
????????????????????try:
????????????????????????self.driver.find_by_text('預(yù)訂')[self.order-1].click()
????????????????????????sleep(1.5)
????????????????????except Exception as e:
????????????????????????print(e)
????????????????????????print('預(yù)訂失敗...')
????????????????????????continue
????????????else:
????????????????while self.driver.url == self.ticket_url:
????????????????????self.driver.find_by_text('查詢').click()
????????????????????count += 1
????????????????????print('第%d次點(diǎn)擊查詢...' % count)
????????????????????try:
????????????????????????for i in self.driver.find_by_text('預(yù)訂'):
????????????????????????????i.click()
????????????????????????????sleep(1)
????????????????????except Exception as e:
????????????????????????print(e)
????????????????????????print('預(yù)訂失敗...')
????????????????????????continue
????????????print('開始預(yù)訂...')
????????????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('確認(rèn)選座...')
????????????self.driver.find_by_id('qr_submit_id').click()
????????????print('預(yù)訂成功...')
????????except Exception as e:
????????????print(e)
if __name__ == '__main__':
????# 用戶名
????username = 'xxxx'
????# 密碼
????password = 'xxx'
????# 車次選擇,0代表所有車次
????order = 2
????# 乘客名叶撒,比如passengers = ['丁小紅', '丁小明']
????# 學(xué)生票需注明绝骚,注明方式為:passengers = ['丁小紅(學(xué)生)', '丁小明']
????passengers = ['丁彥軍']
????# 日期,格式為:'2018-01-20'
????dtime = '2018-01-19'
????# 出發(fā)地(需填寫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腳本吧哪审,爬取某租房網(wǎng)站的房源信息蛾魄,利用高德的 js API 在地圖上標(biāo)出房源地點(diǎn)虑瀑,劃出距離工作地點(diǎn)1小時內(nèi)可到達(dá)的范圍湿滓。
對比租金等,輕輕松松選出最適合的房子舌狗。
代碼
鏈家的房租網(wǎng)站
兩個導(dǎo)入的包
1.requests 用來過去網(wǎng)頁內(nèi)容
2.BeautifulSoup
import time
import pymssql
import requests
from bs4 import BeautifulSoup
# https://wh.lianjia.com/zufang/
#獲取url中下面的內(nèi)容
def get_page(url):
responce = requests.get(url)
soup = BeautifulSoup(responce.text,'lxml')
return soup
#封裝成函數(shù)叽奥,作用是獲取列表下的所有租房頁面的鏈接,返回一個鏈接列表
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
#鏈接數(shù)據(jù)庫
server="192.168.xx.xx" #換成自己的服務(wù)器信息
user="liujiepeng"
password="xxxxx" #自己的數(shù)據(jù)庫用戶名和密碼
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() #游標(biāo)痛侍,開拓新的窗口
#cursor1 = conn.cursor()
cursor.execute(sql) #執(zhí)行sql語句
conn.commit() #提交 朝氓,更新sql 語句
links = get_links('https://wh.lianjia.com/zufang/')
count = 1
for link in links:
#time.sleep(2)
print('獲取一個數(shù)據(jù)成功')
house = get_house_info(link)
insert(conn,house)
print("第%s個數(shù)據(jù)魔市,存入數(shù)據(jù)庫成功!"%(count))
count = count+1
#print(house["價格"],end='\r')
4赵哲、Python找回女神撤回的消息
除了這些日常操作待德,麥教授說幾個你想不到的吧。
當(dāng)自己一直喜歡的女神發(fā)給自己一個消息的時候枫夺,還沒來得及看将宪,就撤回了。
是不是自己在心中"YY"橡庞,她是不是發(fā)了什么较坛,然后你問她的時候,她卻說沒什么扒最。
學(xué)會Python丑勤,你可以做一個程序,把私聊撤回的信息可以收集起來并發(fā)送到個人微信的文件傳輸助手吧趣。
5法竞、Python自己寫小游戲
用Python寫幾個小游戲玩玩也不過是幾十行代碼的事,比如寫個貪吃蛇强挫!
還記得之前火爆一時的跳一跳爪喘,如果你早點(diǎn)學(xué)會Python,就可以常年占據(jù)排行榜第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函數(shù)
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函數(shù)
def main():
?# 初始化pygame
?pygame.init()
?fpsClock = pygame.time.Clock()
?# 創(chuàng)建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
?# 根據(jù)方向移動蛇頭的坐標(biāo)
?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] < 0:
?gameOver(playSurface)
?if snakePosition[1] > 460 or snakePosition[1] < 0:
?for snakeBody in snakeSegments[1:]:
?if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
?gameOver(playSurface)
?# 控制游戲速度
?fpsClock.tick(5)
if __name__ == "__main__":
?main()
6侦鹏、Python爬取你想要的信息
還可以用python爬取電影分析影評,用詞云進(jìn)行展示效果:
寫幾行代碼浪漫一把也是可以的臀叙,你也可以把里面的字符換成愛人的名字略水,做成浪漫的云圖詞!
7劝萤、Python看看你朋友圈都是什么樣的人
掌握python以后渊涝,你玩微信別人也玩微信。
但是你可以得到不一樣的騷操作床嫌,幾十行代碼掌握你朋友圈都是些什么樣的人跨释!
比如?爬取微信好友男女比例并進(jìn)行可視化
再來看看你的好友都來自哪個地方
這還不夠厌处,來把好友的個性簽名也玩出逼格鳖谈,做個創(chuàng)意的文字圖,看看大家都在說什么
溫馨小提示阔涉,如果分析的對象換成你的用戶們...是不是業(yè)績能蹭蹭上漲缆娃?
8捷绒、Python自己做小動畫
還可以用字符串跳一段MV,成為B站大佬贯要,使用 OpenCV 處理圖片視頻暖侨,將視頻轉(zhuǎn)為字符畫序列,再在終端中播放字符動畫崇渗。
9它碎、Python鑒黃
看看Python還能用來干嘛
《圖片就不放了?怕被舉報?自行想象》
哈哈?可以用來emmm 鑒黃!
使用?Python3 去識別圖片是否為色情圖片显押,利用PIL 這個圖像處理庫扳肛,會編寫算法來劃分圖像的皮膚區(qū)域。
其中涉及到Python 3 基礎(chǔ)知識乘碑,膚色像素檢測與皮膚區(qū)域劃分算法挖息。
是不是萬萬沒想到?
10兽肤、PythonAI醫(yī)療
還被用進(jìn)醫(yī)療的領(lǐng)域套腹。
典型如騰訊覓影這樣的產(chǎn)品,用于AI醫(yī)學(xué)圖像分析资铡,在癌癥的早期識別上电禀,人工智能對拍片的識別能力,也已經(jīng)超過人類醫(yī)生笤休。
Python能做的好玩又實(shí)用的事情實(shí)在太多啦尖飞!歡迎留言一起分享討論
不一定要你學(xué)的非常專業(yè)才可以實(shí)現(xiàn),里面有些也是非程序員Python用戶做出來的好玩的東西店雅,期待著你利用Python 去做出更多有趣的事情政基!
最后多說一句,小編是一名python開發(fā)工程師闹啦,這里有我自己整理了一套最新的python系統(tǒng)學(xué)習(xí)教程沮明,包括從基礎(chǔ)的python腳本到web開發(fā)、爬蟲窍奋、數(shù)據(jù)分析荐健、數(shù)據(jù)可視化、機(jī)器學(xué)習(xí)等琳袄。想要這些資料的可以加小編的python學(xué)習(xí)交流企鵝群:1075110200江场,配套資料可以找管理小姐姐免費(fèi)領(lǐng)取。