Python으로 일상 작업을 자동화하는 방법(2부)

DDD
풀어 주다: 2024-10-19 06:15:01
원래의
762명이 탐색했습니다.

How to Automate Everyday Tasks with Python (Part 2)

작가: 트릭스 사이러스

Waymap 침투 테스트 도구: 여기를 클릭하세요
TrixSec Github: 여기를 클릭하세요

1부에서는 Python을 사용하여 파일 관리, 웹 스크래핑, 이메일 전송, Google 스프레드시트 및 시스템 모니터링을 자동화하는 방법을 살펴보았습니다. 2부에서는 API 자동화, 스크립트 예약, 자동화와 타사 서비스 통합 등의 고급 작업을 계속해서 다룰 것입니다.

7. API 요청 자동화

많은 웹 서비스는 프로그래밍 방식으로 플랫폼과 상호 작용할 수 있는 API를 제공합니다. 요청 라이브러리를 사용하면 API에서 데이터 가져오기, 업데이트 게시, 클라우드 서비스에서 CRUD 작업 수행과 같은 작업을 쉽게 자동화할 수 있습니다.

import requests

# OpenWeatherMap API configuration
api_key = 'your_api_key'
city = 'New York'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'

# Send a GET request to fetch weather data
response = requests.get(url)
data = response.json()

# Extract temperature information
temperature = data['main']['temp']
weather = data['weather'][0]['description']

print(f"Temperature: {temperature}°K")
print(f"Weather: {weather}")
로그인 후 복사
로그인 후 복사

이 스크립트는 OpenWeatherMap API에서 특정 도시의 현재 날씨 데이터를 가져와 표시합니다.

8. Python으로 작업 예약

특정 시간이나 간격으로 실행되도록 작업을 자동화해야 하는 경우가 있습니다. Python의 일정 라이브러리를 사용하면 특정 시간에 자동으로 실행되는 작업을 쉽게 설정할 수 있습니다.

import schedule
import time

# Task function to be executed
def task():
    print("Executing scheduled task...")

# Schedule the task to run every day at 9 AM
schedule.every().day.at("09:00").do(task)

# Keep the script running to check the schedule
while True:
    schedule.run_pending()
    time.sleep(1)
로그인 후 복사
로그인 후 복사

이 스크립트는 작업이 계속 실행되도록 간단한 예약 루프를 사용하여 매일 오전 9시에 작업이 실행되도록 예약합니다.

9. 데이터베이스 운영 자동화

Python은 데이터베이스와 상호 작용하고, 데이터 입력을 자동화하고, 레코드 읽기, 업데이트, 삭제와 같은 작업을 수행하는 데 사용할 수 있습니다. sqlite3 모듈을 사용하면 SQLite 데이터베이스를 관리할 수 있으며, 다른 라이브러리(예: psycopg2 또는 MySQLdb)는 PostgreSQL 및 MySQL과 함께 작동합니다.

import sqlite3

# Connect to SQLite database
conn = sqlite3.connect('tasks.db')

# Create a cursor object to execute SQL commands
cur = conn.cursor()

# Create a table for storing tasks
cur.execute('''CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, task_name TEXT, status TEXT)''')

# Insert a new task
cur.execute("INSERT INTO tasks (task_name, status) VALUES ('Complete automation script', 'Pending')")

# Commit changes and close the connection
conn.commit()
conn.close()
로그인 후 복사

이 스크립트는 SQLite 데이터베이스를 생성하고 "작업" 테이블을 추가하며 데이터베이스에 새 작업을 삽입합니다.

10. Excel 파일 관리 자동화

Python은 openpyxl 또는 pandas 라이브러리와 함께 Excel 파일 읽기, 쓰기, 수정을 자동화하는 데 사용할 수 있습니다. 이는 데이터 분석 및 보고 작업을 자동화하는 데 특히 유용합니다.

import pandas as pd

# Read Excel file
df = pd.read_excel('data.xlsx')

# Perform some operation on the data
df['Total'] = df['Price'] * df['Quantity']

# Write the modified data back to a new Excel file
df.to_excel('updated_data.xlsx', index=False)
로그인 후 복사

이 스크립트는 Excel 파일을 읽고, 데이터에 대한 계산을 수행하고, 업데이트된 데이터를 새 파일에 씁니다.

11. Selenium으로 브라우저 상호작용 자동화

Python은 Selenium을 사용하여 계정 로그인, 양식 작성, 반복적인 웹 작업 수행 등 웹 브라우저와의 상호 작용을 자동화할 수 있습니다.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Set up the browser driver
driver = webdriver.Chrome()

# Open the login page
driver.get('https://example.com/login')

# Locate the username and password fields, fill them in, and log in
username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')
username.send_keys('your_username')
password.send_keys('your_password')
password.send_keys(Keys.RETURN)

# Close the browser
driver.quit()
로그인 후 복사

이 스크립트는 웹 브라우저를 열고 로그인 페이지로 이동한 후 자격 증명을 입력하고 자동으로 로그인합니다.

12. 클라우드 서비스 자동화

Python은 AWS, Google Cloud, Azure와 같은 클라우드 서비스와 잘 통합됩니다. boto3 라이브러리를 사용하면 AWS에서 S3 버킷, EC2 인스턴스 및 Lambda 함수 관리와 같은 작업을 자동화할 수 있습니다.

import requests

# OpenWeatherMap API configuration
api_key = 'your_api_key'
city = 'New York'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'

# Send a GET request to fetch weather data
response = requests.get(url)
data = response.json()

# Extract temperature information
temperature = data['main']['temp']
weather = data['weather'][0]['description']

print(f"Temperature: {temperature}°K")
print(f"Weather: {weather}")
로그인 후 복사
로그인 후 복사

이 스크립트는 AWS S3에 연결하고, 모든 버킷을 나열하고, 새 버킷을 생성하고, 여기에 파일을 업로드합니다.

13. PDF 조작 자동화

PyPDF2 라이브러리를 사용하면 Python에서 PDF 파일의 텍스트 병합, 분할, 추출과 같은 작업을 자동화할 수 있습니다.

import schedule
import time

# Task function to be executed
def task():
    print("Executing scheduled task...")

# Schedule the task to run every day at 9 AM
schedule.every().day.at("09:00").do(task)

# Keep the script running to check the schedule
while True:
    schedule.run_pending()
    time.sleep(1)
로그인 후 복사
로그인 후 복사

이 스크립트는 여러 PDF 파일을 단일 파일로 병합합니다.

~트릭섹

위 내용은 Python으로 일상 작업을 자동화하는 방법(2부)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!