Use Python to simulate the like assistant

Mondo Technology Updated on 2024-02-07

In the past, the company has been arranging various learning tasks, **There are many chapters**, some are technical and some are policy-related, and if you do not complete the learning tasks on time, you will be notified. However, these learning contents are not necessarily helpful, so everyone has developed the habit of brushing up on the class, that is, clicking on the ** and letting it hang there. But there is a problem,**The process will detect whether the user has operated,If the detection is not operated for a long time, the pop-up box will prompt,Only click the continue button on the pop-up box to continue**,This leads us to often pay attention to whether the page is paused when brushing the class,The efficiency of brushing the class is a bit low。 To this end, a desktop icon detection gadget was made, which detected that after a specific icon appeared on the desktop, it simulated mouse clicks to complete the function of continuing.

That's where one comes inpythonLibrary——pyautogui。Here's how this library is used.,And use this library to make an assistant for brushing likes.,But it's recommended not to use it to really brush likes.。

pyautoguiis a Python library for programmatically controlling mouse and keyboard operations that can be used to automate tests, tasks, and other requirements. Here's onepyautoguiBasic tutorials.

First, it needs to be installedpyautogui

pip install pyautogui

pyautoguiYou can control the mouse movement to a specific location on the screen. This can be passedmovetofunction implementation, which requires x and y coordinates as arguments.

import pyautogui

Move the mouse to the (100, 100) position of the screen.

pyautogui.moveto(100, 100, duration=1)

durationThe parameter is optional and represents the time it takes to move to the specified location in seconds.

useclickFunctions can simulate mouse clicks or specify where they are clicked.

Left-click at the current location. 

pyautogui.click()

Right-click on the screen (200, 200).

pyautogui.click(200, 200, button='right')

scrollFunctions can scroll the mouse. A positive number means to scroll up, and a negative number means to scroll down. This unit does not directly correspond to the number of pixels on the screen, but rather depends on the scrolling settings of the operating system and the application. For example, in some text editors or web browsers, a line may be defined as the height of a line of text, while in other contexts it may depend on the system's scroll speed setting.

Scroll up. 

pyautogui.scroll(200)

Scroll down.

pyautogui.scroll(-200)

pyautoguiIt can also simulate keyboard actions, such as keystrokes, text input, etc.

Press and release the spacebar. 

pyautogui.press('space')

Enter a string.

pyautogui.write('hello, pyautogui!', interval=0.25)

intervalThe parameter represents the delay time between each character in seconds.

pyautoguiScreenshots of the screen can be captured, which is useful for automated testing and monitoring.

Capture a full-screen screenshot. 

screenshot = pyautogui.screenshot()

screenshot.s**e('screenshot.png')

pyautoguiThe location of the image can be found on the screen. If found, a quadruple is returned(left, top, width, height), which indicates the position and size of the found image on the screen. If no matching image is found, the function returnsnone。It can be passedconfidenceparameters increase the fault tolerance of the search. confidenceParameters are used to specify the accuracy of the match, ranging from 0 to 1. Note, useconfidenceParameters need to be installedopencv-pythonLibrary——

location = pyautogui.locateonscreen('button.png', confidence=0.9)

usepyautogui, especially when controlling the mouse and keyboard automatically, make sure that there are adequate safety measures, such as setting a delay or usepyautogui.failsafe = trueEnable fail-safe features. When the fail-safe feature is enabled, moving the mouse to the top left corner of the screen will throwpyautogui.failsafeexceptionto interrupt the script. Before you run the automation script, make sure you understand what you'll do to prevent accidental actions on your mouse and keyboard or other issues. At the heart of the tool is the use of python librariespyautoguipynputwithopencv-pythonto automate interactions. The workflow is as follows:

Open the Zhihu follow pageFirst of all, manually open the Zhihu follow page and prepare to start the automation operation. The screen detects the approval icon: The tool will constantly scan the screen for a specific endorsement icon. Simulate user reading: Once the approval icon is found, the tool simulates clicking on the line above the icon to open the full text, and then simulates scrolling up and down with the mouse to simulate the reading process. Auto-like: After reading, the tool simulates clicking the agree icon to complete the like operation. Exit reading and continue testing: After recognizing the collapsed icon, exit the reading state and simulate mouse swiping to detect the next approval icon. Through this series of operations, the tool can automatically like articles on Zhihu, simulating the normal browsing behavior of users.

Approve icon

Collapse icon

Liked icon.

Project ** is hosted ongithub, which can be accessed via the following link*** and icon: github-

import random

import time

import pyautogui

from pynput import keyboard

import threading

Listen for the ESC key identifier (stop running when the ESC key is heard).

listener_esc = false

The path of the image sample.

agree_path = 'image/agree.png'

read_more_path = 'image/read_more.png'

close_path = 'image/close.png'

The length of the break (in s, preferably longer).

sleep_time = 1

Confidence level (it is recommended to increase it, otherwise it is easy to touch it by mistake).

confidence = 0.8

Mouse scroll speed.

scroll_speed = 10

def on_press(key):

The action when the key is pressed.

try:if key == keyboard.key.esc:

When the ESC key is detected, the message is output and the listening is stopped.

print('The esc key is pressed to stop listening. ')

ESC has been pressed.

global listener_esc

listener_esc = true

Returns false to stop ***

return false

except attributeerror:

passdef get_a_number(a, b):

Generate a random number [a, b].

return:

return random.random().randint(a, b)

def on_release(key):

The operation when the key is released.

passdef start_listener():

Listen for the ESC key.

return:

with keyboard.listener(on_press=on_press, on_release=on_release) as listener:

listener.join()

def reading():

Simulated reading. 1. Roll the mouse randomly.

2. Scroll the number of pixel rows randomly.

return:

Scroll the mouse up and down randomly ().

scroll_times = get_a_number(1, 3)

while scroll_times > 0 and not listener_esc:

The number of random scrolling pixel rows.

lines = get_a_number(50, 100)

Swipe down.

for _ in range(int(lines / scroll_speed)):

pyautogui.scroll(-scroll_speed)

time.sleep(sleep_time)

Swipe up to be able to return to the position just now.

for _ in range(int(lines / scroll_speed)):

pyautogui.scroll(scroll_speed)

time.sleep(sleep_time)

scroll_times -= 1

def close():

The simulation closes the reading, and the loop is to prevent the coordinates from being inaccurate and not turning off.

return:

try:close_location = pyautogui.locateonscreen(close_path, confidence=confidence)

while close_location:

Calculate the image center point.

center = pyautogui.center(close_location)

pyautogui.click(center)

print(f"close-clicked on ")

time.sleep(sleep_time)

close_location = pyautogui.locateonscreen(close_path, confidence=confidence)

except pyautogui.failsafeexception:

print("close not found")

return

def do_read(x, y):

Simulate clicking "Read More".

param x:

param y: Agree, click about 50 pixels above to view the full article.

return:

Look for an image on the screen to read the full article.

if not listener_esc:

Click here to view the full article.

pyautogui.click(x, y)

print(f"read more-clicked on , ")

Load the content.

time.sleep(sleep_time)

Read. reading()

def do_click():

Mock likes. :return:

Check if the esc key is pressed, and if so, exit the loop.

while not listener_esc:

Give yourself some time to get ready to switch to the target app window.

time.sleep(sleep_time)

try: Find the favor image on the screen, and the confidence parameter can be adjusted to suit the accuracy requirements of the image match.

agree_location = pyautogui.locateonscreen(agree_path, confidence=confidence)

if agree_location:

Calculate the image center point.

center = pyautogui.center(agree_location)

x, y = center

Simulated reading.

do_read(x, y - 50)

Thumbs up. if not listener_esc:

# pyautogui.click(x, y) prevents deviations caused by movement of coordinates and reacquires approval coordinates.

agree_location = pyautogui.locateonscreen(agree_path, confidence=confidence)

center = pyautogui.center(agree_location)

pyautogui.click(center)

print(f"agree - clicked on ")

Click the Close button.

close()

except pyautogui.imagenotfoundexception:

print("agree not found. trying again...")

Pause briefly so that loops don't execute too often.

time.sleep(sleep_time)

Scroll down, about 200 pixels down.

for _ in range(int(200 / scroll_speed)):

pyautogui.scroll(-scroll_speed)

print("exited.")

Create and start a thread listening to the esc key.

listener_thread1 = threading.thread(target=start_listener)

listener_thread1.start()

The ** here can be executed without being blocked.

print("like mode begin...")

do_click()

print("like mode end...")

In order to run this tool, the following python libraries need to be installed:

pip install pyautogui pynput opencv-python

pyautogui: Used to simulate mouse clicks and scrolls. pynput: Used to simulate keyboard input and capture exit signals. opencv-python: Used for image recognition, detecting specific icons on the screen. Coordinate accuracy: Make sure that the pixel coordinates used are the upper left corner, not the center coordinates, to improve recognition accuracy. Icon clarity: Screenshots of the Like and Close buttons should be clear, and the zoom level of the webpage should be the same as when the program is running. Anti-detection measures: In order to avoid being detected by the platform, it is recommended to set a long random rest period. Fair Use: This item is for study and research use only and should not be used for any violations.
**The rest intervals in the demo were shortened and doubled.

February** Dynamic Incentive Program

Related Pages