Python from 0 to Hero 시리즈에 다시 오신 것을 환영합니다! 지금까지 우리는 급여 및 HR 시스템과 관련된 작업을 위해 데이터를 조작하고 강력한 외부 라이브러리를 사용하는 방법을 배웠습니다. 하지만 실시간 데이터를 가져오거나 외부 서비스와 상호 작용해야 하는 경우에는 어떻게 해야 할까요? 이것이 바로 API와 웹 스크래핑이 작동하는 곳입니다.
이 강의에서 다룰 내용은 다음과 같습니다.
이 강의가 끝나면 외부 데이터 검색을 자동화하여 HR 시스템을 더욱 동적이고 데이터 중심적으로 만들 수 있게 됩니다.
API(응용 프로그래밍 인터페이스)는 서로 다른 소프트웨어 응용 프로그램이 서로 통신할 수 있도록 하는 일련의 규칙입니다. 간단히 말해서, 코드에서 직접 다른 서비스나 데이터베이스와 상호 작용할 수 있습니다.
예를 들어:
대부분의 API는 REST(Representational State Transfer)라는 표준을 사용합니다. 이를 통해 HTTP 요청(예: GET 또는 POST)을 보내 데이터에 액세스하거나 업데이트할 수 있습니다.
Python의 요청 라이브러리를 사용하면 API 작업이 쉬워집니다. 다음을 실행하여 설치할 수 있습니다:
pip install requests
GET 요청을 사용하여 API에서 데이터를 가져오는 방법에 대한 간단한 예부터 시작하겠습니다.
import requests # Example API to get public data url = "https://jsonplaceholder.typicode.com/users" response = requests.get(url) # Check if the request was successful (status code 200) if response.status_code == 200: data = response.json() # Parse the response as JSON print(data) else: print(f"Failed to retrieve data. Status code: {response.status_code}")
이 예에서는:
급여 목적으로 실시간 세율을 가져오고 싶다고 가정해 보겠습니다. 많은 국가에서 세율에 대한 공개 API를 제공합니다.
이 예에서는 세금 API에서 데이터 가져오기를 시뮬레이션합니다. 실제 API를 사용해도 로직은 비슷할 것입니다.
import requests # Simulated API for tax rates api_url = "https://api.example.com/tax-rates" response = requests.get(api_url) if response.status_code == 200: tax_data = response.json() federal_tax = tax_data['federal_tax'] state_tax = tax_data['state_tax'] print(f"Federal Tax Rate: {federal_tax}%") print(f"State Tax Rate: {state_tax}%") # Use the tax rates to calculate total tax for an employee's salary salary = 5000 total_tax = salary * (federal_tax state_tax) / 100 print(f"Total tax for a salary of ${salary}: ${total_tax:.2f}") else: print(f"Failed to retrieve tax rates. Status code: {response.status_code}")
이 스크립트는 실제 세율 API와 함께 작동하도록 조정될 수 있으며 급여 시스템을 최신 세율로 최신 상태로 유지하는 데 도움이 됩니다.
API는 데이터를 가져오는 데 선호되는 방법이지만 모든 웹사이트에서 API를 제공하는 것은 아닙니다. 이러한 경우 웹 스크래핑을 사용하여 웹페이지에서 데이터를 추출할 수 있습니다.
Python의 BeautifulSoup 라이브러리는 요청과 함께 웹 스크래핑을 쉽게 만듭니다. 다음을 실행하여 설치할 수 있습니다:
pip install beautifulsoup4
회사의 HR 웹사이트에서 직원 복리후생에 대한 데이터를 긁어내고 싶다고 상상해 보세요. 기본적인 예는 다음과 같습니다.
import requests from bs4 import BeautifulSoup # URL of the webpage you want to scrape url = "https://example.com/employee-benefits" response = requests.get(url) # Parse the page content with BeautifulSoup soup = BeautifulSoup(response.content, 'html.parser') # Find and extract the data you need (e.g., benefits list) benefits = soup.find_all("div", class_="benefit-item") # Loop through and print out the benefits for benefit in benefits: title = benefit.find("h3").get_text() description = benefit.find("p").get_text() print(f"Benefit: {title}") print(f"Description: {description}\n")
이 예에서는:
이 기술은 혜택, 채용 공고, 급여 벤치마크 등 HR 관련 데이터를 웹에서 수집하는 데 유용합니다.
모든 것을 하나로 모아 실제 HR 시나리오에 대한 API 사용과 웹 스크래핑을 결합한 미니 애플리케이션을 만들어 보겠습니다. 직원의 총 비용을 계산합니다.
잘:
import requests from bs4 import BeautifulSoup # Step 1: Get tax rates from API def get_tax_rates(): api_url = "https://api.example.com/tax-rates" response = requests.get(api_url) if response.status_code == 200: tax_data = response.json() federal_tax = tax_data['federal_tax'] state_tax = tax_data['state_tax'] return federal_tax, state_tax else: print("Error fetching tax rates.") return None, None # Step 2: Scrape employee benefit costs from a website def get_benefit_costs(): url = "https://example.com/employee-benefits" response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.content, 'html.parser') # Let's assume the page lists the monthly benefit cost benefit_costs = soup.find("div", class_="benefit-total").get_text() return float(benefit_costs.strip("$")) else: print("Error fetching benefit costs.") return 0.0 # Step 3: Calculate total employee cost def calculate_total_employee_cost(salary): federal_tax, state_tax = get_tax_rates() benefits_cost = get_benefit_costs() if federal_tax is not None and state_tax is not None: # Total tax deduction total_tax = salary * (federal_tax state_tax) / 100 # Total cost = salary benefits tax total_cost = salary benefits_cost total_tax return total_cost else: return None # Example usage employee_salary = 5000 total_cost = calculate_total_employee_cost(employee_salary) if total_cost: print(f"Total cost for the employee: ${total_cost:.2f}") else: print("Could not calculate employee cost.")
이는 단순화된 예이지만 다양한 소스(API 및 웹 스크래핑)의 데이터를 결합하여 보다 역동적이고 유용한 HR 애플리케이션을 만드는 방법을 보여줍니다.
웹 스크래핑은 강력하지만 따라야 할 몇 가지 중요한 모범 사례가 있습니다.
이번 강의에서는 API를 사용하여 외부 서비스와 상호작용하는 방법과 웹 스크래핑을 통해 웹사이트에서 데이터를 추출하는 방법을 살펴보았습니다. 이러한 기술은 특히 HR 환경에서 외부 데이터를 Python 애플리케이션에 통합할 수 있는 무한한 가능성을 열어줍니다.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3