What are Python's sacred honey operations?Attached Code

Keywords: Python SQL Database Mobile

Someone said,'Python can do everything from nurturing sisters to dressing up x, except it can't have children!Anything will do!"

Download video?I use Python;

Play a jump?I jumped to 4999 with Python;

Sister?Still using Python;

Grab red bags for train tickets?Yes, it's Python.

Even if I'm sorting out files, I'll use Python...

Here are some Python sauce actions to share with you in detail:

1. Python lets you stop missing red envelopes

Have you missed hundreds of millions of people who have just passed the year and experienced the battle of robbing red envelopes?

With black technology Python, develop a small assistant on WeChat, and never worry about missing a huge red envelope again!

There are two main parts to the implementation code:

1. Receiving red-packet messages, it is more difficult to get data directly from WeChat on the mobile phone. The mainstream method is to obtain data through the Web version of WeChat.

Because the message interface of the Web page version can be analyzed by packet capture, it is easier to obtain and use.

2. Notification. The easiest way to notify is to make a sound. If that's not enough, you can pop up a window.

# Open Mobile WeChat
poco(text='WeChat').click()
#Get the names of all group chats on the current page
 //Element identity of group chat message Chat_msg = poco(name='com.tencent.mm:id/d1v').offspring('com.tencent.mm:id/b6e')
# Get the names of all group chats on the current page
Chat_names = []
Chat_names = list(map(lambda x: x.get_text(), Chat_msg))
# Specify the group chat name for the red bag
chat = input('Please specify group chat name:')
if chat in Chat_names:
 index = Chat_names.index(chat)
 # Click to enter the specified group chat
 Chat_msg[index].click()
//On the WeChat page, get all the message elements on the current page.
msg_list = poco("android.widget.ListView").children()
#   Traverse messages and find red bags
for msg in msg_list:
# Identification of WeChat Red Pack
 LuckyMoney = msg.offspring('com.tencent.mm:id/aql')
 # Identification of an expired red packet (e.g. received or received)
 Invalid = msg.offspring('com.tencent.mm:id/aqk')
 # Judge if the red bag is valid and grab it!
 if LuckyMoney:
 pass
    #Traverse messages and find red bags
if Invalid.exists() and (Invalid.get_text()=='Received' or Invalid.get_text()=='Has been taken over'):
print(f'Red Pack is no longer valid, skip...')
 continue
else:
 print(f'Discover a new red bag, grab it!')
 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')
#Initializer
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 helps you grab your train ticket

Python is not only good at grabbing red bags, but also good at grabbing train tickets. Maybe the tickets you bought in that year were grabbed by Python.

Is it hard for everyone to go home to grab tickets in the New Year? You can write a software for grabbing tickets in the New Year!

Use Python3 to grab ticket information of 12306 website, prompt and order automatically.

from splinter.browser import Browser
from time import sleep
import traceback

class Buy_Tickets(object):
    # Define instance properties, initialize
    def __init__(self, username, passwd, order, passengers, dtime, starts, ends):
        self.username = username
        self.passwd = passwd
        # Number of trips, 0 for all trips, from top to bottom, 1 for all trips, and so on
        self.order = order
        # Passenger name
        self.passengers = passengers
        # Start and end points
        self.starts = starts
        self.ends = ends
        # date
        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'
    # Logon Function Implementation
    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('Please enter the verification code...')
        while True:
            if self.driver.url != self.initMy_url:
                sleep(1)
            else:
                break
    # Ticket Buying Function Realization
    def start_buy(self):
        self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)
        #Operation of window size
        self.driver.driver.set_window_size(700, 500)
        self.login()
        self.driver.visit(self.ticket_url)
        try:
            print('Start buying tickets...')
            # Load query information
            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('query').click()
                    count += 1
                    print('No.%d Second Click Query...' % count)
                    try:
                        self.driver.find_by_text('Book')[self.order-1].click()
                        sleep(1.5)
                    except Exception as e:
                        print(e)
                        print('Reservation failed...')
                        continue
            else:
                while self.driver.url == self.ticket_url:
                    self.driver.find_by_text('query').click()
                    count += 1
                    print('No.%d Second Click Query...' % count)
                    try:
                        for i in self.driver.find_by_text('Book'):
                            i.click()
                            sleep(1)
                    except Exception as e:
                        print(e)
                        print('Reservation failed...')
                        continue
            print('Start Booking...')
            sleep(1)
            print('Start selecting users...')
            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('place order...')
            # 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('Confirm seat selection...')
            self.driver.find_by_id('qr_submit_id').click()
            print('Successful Booking...')
        except Exception as e:
            print(e)

if __name__ == '__main__':
    # User name
    username = 'xxxx'
    # Password
    password = 'xxx'
    # Number of trips, 0 for all trips
    order = 2
    # Passenger names, such as passengers = ['Ding Xiaohong','Ding Xiaoming']
    # Student tickets need to be indicated by passengers = ['Ding Xiaohong (student)','Ding Xiaoming']
    passengers = ['Ding Yanjun']
    # Date in the format'2018-01-20'
    dtime = '2018-01-19'
    # Origin (cookie value to be filled in)
    starts = '%u5434%u5821%2CWUY' #wubu
    # Destination (cookie value to be filled in)
    ends = '%u897F%u5B89%2CXAY' #Xi'an

    # xb =['hard seat'] 
    # pz=['Adult Ticket']

    Buy_Tickets(username, password, order, passengers, dtime, starts, ends).start_buy()

3. Python helps you choose a house

Many friends want to start renting after the year, is it too tired to check one by one?

Write a Python script to crawl the source information of a rental website, use Golden's js API to map the source location, and map out the range within an hour from the workplace.

Compare rents, etc. to easily choose the most suitable house.

Code

//Chain House Rent Website
//Two imported packages
1.requests Used for past web content
2.BeautifulSoup
import time
import pymssql
import requests
from bs4 import BeautifulSoup
# https://wh.lianjia.com/zufang/
#Get the following in the url
def get_page(url):
responce = requests.get(url)
soup = BeautifulSoup(responce.text,'lxml')
return soup
#Encapsulated as a function to get links to all rental pages under the list and return a list of links
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
#Collect information about a house
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:] #String Slicing Tool
layout = house_info[1].text[5:]
info={
'Price':price,
'Company':unit,
'The measure of area':area,
'Household type':layout
}
return info
#Link Database
server="192.168.xx.xx" #Replace with your own server information
user="liujiepeng"
password="xxxxx" #Your own database user name and password
conn=pymssql.connect(server,user,password,database="house")
def insert(conn,house):
#sql_values = values.format(house['price'], house['unit'], house['area'],
#house ['family type'])
sql = "insert into [house].dbo.lianjia(price,unit,area,layout)values('%s','%s','%s','%s')"%(house["Price"],house["Company"],house["The measure of area"],house["Household type"])
print(sql)
cursor = conn.cursor() #Cursor, Open New Window
#cursor1 = conn.cursor()
cursor.execute(sql) #Execute sql statement
conn.commit() #Submit, update sql statement
links = get_links('https://wh.lianjia.com/zufang/')
count = 1
for link in links:
#time.sleep(2)
print('Get a data success')
house = get_house_info(link)
insert(conn,house)
print("No.%s Successfully saved data in database!"%(count))
count = count+1
#print(house [price], end='\r')

4. Python retrieves the message that the goddess withdrew

In addition to these daily operations, Professor McDonald said something you didn't expect.

When the goddess that I have always liked sent me a message, it was withdrawn before I could see it.

Did she have "YY" in her mind? What happened to her? Then when you asked her, she said nothing.

With Python, you can do a program that collects information withdrawn from private conversations and sends it to your personal WeChat file transfer assistant.

5. Python Writes Games by himself

Writing a few little games to play with Python is just a matter of dozens of lines of code, like writing a snake!

Remember the big jump before. If you learn Python earlier, you'll be at the top of the list all year round, or fully automatic. That's fun!

Skip code:

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()

//Snake Snake Code:

#!/usr/bin/env python
import pygame,sys,time,random
from pygame.locals import *
# Define color variables
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
greyColour = pygame.Color(150,150,150)

# Define gameOver function
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()

# Define main function
def main():
 # Initialize pygame
 pygame.init()
 fpsClock = pygame.time.Clock()
 # Create pygame display layer
 playSurface = pygame.display.set_mode((640,480))
 pygame.display.set_caption('Raspberry Snake')

 # initialize variable
 snakePosition = [100,100]
 snakeSegments = [[100,100],[80,100],[60,100]]
 raspberryPosition = [300,300]
 raspberrySpawned = 1
 direction = 'right'
 changeDirection = direction
 while True:
 # Detect pygame events such as keystrokes
 for event in pygame.event.get():
 if event.type == QUIT:
 pygame.quit()
 sys.exit()
 elif event.type == KEYDOWN:
 # Judging keyboard events
 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))
 # Determine if the opposite direction was entered
 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
 # Move snake head coordinates in direction
 if direction == 'right':
 snakePosition[0] += 20
 if direction == 'left':
 snakePosition[0] -= 20
 if direction == 'up':
 snakePosition[1] -= 20
 if direction == 'down':
 snakePosition[1] += 20
 # Increase the length of the snake
 snakeSegments.insert(0,list(snakePosition))
 # Determine if you ate raspberries
 if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
 raspberrySpawned = 0
 else:
 snakeSegments.pop()
 # If you eat raspberries, regenerate them
 if raspberrySpawned == 0:
 x = random.randrange(1,32)
 y = random.randrange(1,24)
 raspberryPosition = [int(x*20),int(y*20)]
 raspberrySpawned = 1
 # Draw pygame display layer
 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))

 # Refresh pygame display layer
 pygame.display.flip()
 # Judging whether to die
 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)
 # Control Game Speed
 fpsClock.tick(5)

if __name__ == "__main__":
 main()

6. Python crawls the information you want

You can also use python to crawl movie reviews and use the word cloud to show the effect:

It's also possible to write a few lines of code to be romantic. You can also change the characters inside to your loved one's name to be a romantic cloud picture word.

7. Python to see what kind of people your circle of friends is

After you master python, you play WeChat with others.

But you can get different Sao operations, dozens of lines of code to know what kind of people your circle of friends are!

For example?Crawl and visualize the ratio of male to female friends in WeChat

Let's see where your friends come from.


That's not enough. Play B-Square with your friend's personality signature, create a creative text map, and see what everyone is saying

Warm tip, if you're analyzing people for your users... can performance stagger?

8. Python makes his own small animations

You can also use a string to jump a MV, become a B-stop geek, use OpenCV to process picture and video, convert the video to a character-picture sequence, and play character animation in the terminal.

9. Python Yellow Discrimination

See what Python can be used for

Pictures Don't Let go for fear of being reported and imagined by yourself

Haha can be used to discriminate yellow with emmm!

Use Python3 to identify whether the picture is a sunny one. Using PIL, an image processing library, an algorithm is written to divide the skin area of the image.

It involves Python 3 basics, skin color pixel detection and skin area division algorithm.

Didn't it come as a surprise?

10. PythonAI Medical

It is also used in the field of medical care.

Typical products such as Tencent Prospect are used for AI medical image analysis. Artificial intelligence has surpassed human doctors in identifying photographs in the early stages of love.

Python can do a lot of fun and useful things!Welcome to leave a message to share the discussion

You don't have to be a very professional to do this. There are some interesting things that non-programmer Python users do, and we expect you to do more interesting things with Python!

Posted by Lonepig on Sun, 26 Apr 2020 09:40:30 -0700