HR Automation のための API と Web スクレイピングの使用に関するレッスン
0 から Hero までの Python シリーズへようこそ!これまでのところ、給与および人事システムに関連するタスクでデータを操作し、強力な外部ライブラリを使用する方法を学びました。しかし、リアルタイム データを取得したり、外部サービスとやり取りしたりする必要がある場合はどうすればよいでしょうか?そこでAPI と Web スクレイピング が登場します。
このレッスンでは以下について説明します:
- API とは何か、またそれらがなぜ役立つのか。
- Python のリクエスト ライブラリを使用して REST API と対話する方法。
- Web スクレイピング テクニックを適用して Web サイトからデータを抽出する方法。
- 給与計算のためのリアルタイムの税率の取得や、Web サイトからの従業員福利厚生データのスクレイピングなどの実用的な例。
このレッスンを終了するまでに、外部データの取得を自動化し、人事システムをより動的でデータ主導型にすることができるようになります。
1. API とは何ですか?
API (アプリケーション プログラミング インターフェイス) は、さまざまなソフトウェア アプリケーションが相互に通信できるようにする一連のルールです。簡単に言うと、コードから直接別のサービスやデータベースと対話できるようになります。
例:
- API を使用して、給与計算用のリアルタイム税率を取得できます。
- HR ソフトウェア API と統合して、従業員データをシステムに直接取り込むことができます。
- または、気象 API を使用して、異常気象条件に基づいて従業員にいつ特別手当を提供するかを知ることもできます。
ほとんどの API は、REST (Representational State Transfer) と呼ばれる標準を使用します。これにより、HTTP リクエスト (GET や POST など) を送信してデータにアクセスしたり、データを更新したりできます。
2. リクエスト ライブラリを使用して API と対話する
Python のリクエスト ライブラリを使用すると、API を簡単に操作できます。次のコマンドを実行してインストールできます:
pip install requests
基本的な API リクエストの作成
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}")
この例では:
- requests.get() 関数を使用して API からデータを取得します。
- リクエストが成功すると、データは JSON として解析され、処理できます。
HR アプリケーションの例: リアルタイムの税金データの取得
給与計算のためにリアルタイムの税率を取得したいとします。多くの国が税率のパブリック 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 で動作するように調整でき、給与システムを最新の税率で最新の状態に保つことができます。
3. Webスクレイピングによるデータ収集
API はデータを取得するための推奨される方法ですが、すべての Web サイトが API を提供しているわけではありません。そのような場合、Web スクレイピングを使用して Web ページからデータを抽出できます。
Python の BeautifulSoup ライブラリとリクエストを使用すると、Web スクレイピングが簡単になります。次のコマンドを実行してインストールできます:
pip install beautifulsoup4
例: Web サイトから従業員福利厚生データを収集する
企業の人事 Web サイトから 従業員福利厚生 に関するデータを収集したいと想像してください。基本的な例を次に示します:
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")
この例では:
- requests.get() を使用して Web ページのコンテンツをリクエストします。
- BeautifulSoup オブジェクトは HTML コンテンツを解析します。
- 次に、find_all() を使用して、関心のある特定の要素 (特典のタイトルや説明など) を抽出します。
この手法は、福利厚生、求人情報、給与ベンチマークなどの人事関連データを Web から収集する場合に役立ちます。
4. 人事アプリケーションでの API と Web スクレイピングの組み合わせ
すべてをまとめて、実際の人事シナリオ用の API の使用と Web スクレイピングを組み合わせたミニアプリケーションを作成しましょう。従業員の総コストを計算します。
次のことを行います:
- Use an API to get real-time tax rates.
- Scrape a webpage for additional employee benefit costs.
Example: Total Employee Cost Calculator
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.")
How It Works:
- The get_tax_rates() function retrieves tax rates from an API.
- The get_benefit_costs() function scrapes a webpage for the employee benefits cost.
- The calculate_total_employee_cost() function calculates the total cost by combining salary, taxes, and benefits.
This is a simplified example but demonstrates how you can combine data from different sources (APIs and web scraping) to create more dynamic and useful HR applications.
Best Practices for Web Scraping
While web scraping is powerful, there are some important best practices to follow:
- Respect the website’s robots.txt: Some websites don’t allow scraping, and you should check their robots.txt file before scraping.
- Use appropriate intervals between requests: Avoid overloading the server by adding delays between requests using the time.sleep() function.
- Avoid scraping sensitive or copyrighted data: Always make sure you’re not violating any legal or ethical rules when scraping data.
Conclusion
In this lesson, we explored how to interact with external services using APIs and how to extract data from websites through web scraping. These techniques open up endless possibilities for integrating external data into your Python applications, especially in an HR context.
以上がHR Automation のための API と Web スクレイピングの使用に関するレッスンの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











LinuxターミナルでPythonバージョンを表示する際の許可の問題の解決策PythonターミナルでPythonバージョンを表示しようとするとき、Pythonを入力してください...

fiddlereveryversings for the-middleの測定値を使用するときに検出されないようにする方法

10時間以内にコンピューター初心者プログラミングの基本を教える方法は?コンピューター初心者にプログラミングの知識を教えるのに10時間しかない場合、何を教えることを選びますか...

PythonのPandasライブラリを使用する場合、異なる構造を持つ2つのデータフレーム間で列全体をコピーする方法は一般的な問題です。 2つのデータがあるとします...

UvicornはどのようにしてHTTPリクエストを継続的に聞きますか? Uvicornは、ASGIに基づく軽量のWebサーバーです。そのコア機能の1つは、HTTPリクエストを聞いて続行することです...

Investing.comの反クラウリング戦略を理解する多くの人々は、Investing.com(https://cn.investing.com/news/latest-news)からのニュースデータをクロールしようとします。
