搜尋
首頁後端開發Python教學課程 使用 API 和 Web 抓取實現 HR 自動化

Lesson  Working with APIs and Web Scraping for HR Automation

歡迎回到我們的Python從0到英雄系列!到目前為止,我們已經學習如何操作資料並使用強大的外部函式庫來執行與工資和人力資源系統相關的任務。但是,如果您需要取得即時數據或與外部服務互動怎麼辦?這就是 API網頁抓取 發揮作用的地方。

在本課中,我們將介紹:

  1. API是什麼以及為何它們有用。
  2. 如何使用 Python 的 requests 函式庫與 REST API 互動。
  3. 如何應用網頁抓取技術從網站擷取資料。
  4. 實際範例,例如取得薪資的即時稅率或從網站抓取員工福利資料。

在本課程結束時,您將能夠自動化外部資料檢索,使您的 HR 系統更加動態和資料驅動。


1.什麼是API?

API(應用程式介面)是一組允許不同軟體應用程式相互通訊的規則。簡而言之,它允許您直接從程式碼與另一個服務或資料庫互動。

例如:

  • 您可以使用 API 取得即時稅率用於薪資計算。
  • 您可以與人力資源軟體 API 集成,將員工資料直接提取到您的系統中。
  • 或您可以使用天氣 API 來了解何時根據極端天氣條件為員工提供特殊福利。

大多數 API 使用名為 REST(表述性狀態傳輸)的標準,它允許您發送 HTTP 請求(如 GET 或 POST)來存取或更新資料。


2. 使用Requests庫與API交互

Python 的 requests 函式庫可以輕鬆使用 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. 網頁抓取來收集數據

雖然 API 是獲取資料的首選方法,但並非所有網站都提供它們。在這些情況下,網頁抓取可用於從網頁中提取資料。

Python 的 BeautifulSoup 函式庫以及要求讓網頁抓取變得簡單。您可以透過運行來安裝它:

pip install beautifulsoup4

範例:從網站上抓取員工福利數據

想像一下您想要從公司的人力資源網站上抓取有關員工福利的資料。這是一個基本範例:

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()請求網頁的內容。
  • BeautifulSoup 物件解析 HTML 內容。
  • 然後,我們使用 find_all() 來提取我們感興趣的特定元素(例如,福利標題和描述)。

此技術對於從網路收集與人力資源相關的資料(例如福利、職位發布或薪資基準)非常有用。


4. 在 HR 應用程式中結合 API 和 Web 抓取

讓我們將所有內容放在一起,創建一個結合 API 使用和 Web 抓取的迷你應用程序,用於真實的 HR 場景:計算員工的總成本

我們會:

  • 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:

  1. The get_tax_rates() function retrieves tax rates from an API.
  2. The get_benefit_costs() function scrapes a webpage for the employee benefits cost.
  3. 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:

  1. Respect the website’s robots.txt: Some websites don’t allow scraping, and you should check their robots.txt file before scraping.
  2. Use appropriate intervals between requests: Avoid overloading the server by adding delays between requests using the time.sleep() function.
  3. 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.

以上是課程 使用 API 和 Web 抓取實現 HR 自動化的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用Python查找文本文件的ZIPF分佈如何使用Python查找文本文件的ZIPF分佈Mar 05, 2025 am 09:58 AM

本教程演示如何使用Python處理Zipf定律這一統計概念,並展示Python在處理該定律時讀取和排序大型文本文件的效率。 您可能想知道Zipf分佈這個術語是什麼意思。要理解這個術語,我們首先需要定義Zipf定律。別擔心,我會盡量簡化說明。 Zipf定律 Zipf定律簡單來說就是:在一個大型自然語言語料庫中,最頻繁出現的詞的出現頻率大約是第二頻繁詞的兩倍,是第三頻繁詞的三倍,是第四頻繁詞的四倍,以此類推。 讓我們來看一個例子。如果您查看美國英語的Brown語料庫,您會注意到最頻繁出現的詞是“th

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

python中的圖像過濾python中的圖像過濾Mar 03, 2025 am 09:44 AM

處理嘈雜的圖像是一個常見的問題,尤其是手機或低分辨率攝像頭照片。 本教程使用OpenCV探索Python中的圖像過濾技術來解決此問題。 圖像過濾:功能強大的工具圖像過濾器

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

Python中的平行和並發編程簡介Python中的平行和並發編程簡介Mar 03, 2025 am 10:32 AM

Python是數據科學和處理的最愛,為高性能計算提供了豐富的生態系統。但是,Python中的並行編程提出了獨特的挑戰。本教程探討了這些挑戰,重點是全球解釋

如何在Python中實現自己的數據結構如何在Python中實現自己的數據結構Mar 03, 2025 am 09:28 AM

本教程演示了在Python 3中創建自定義管道數據結構,利用類和操作員超載以增強功能。 管道的靈活性在於它能夠將一系列函數應用於數據集的能力,GE

python對象的序列化和避難所化:第1部分python對象的序列化和避難所化:第1部分Mar 08, 2025 am 09:39 AM

Python 對象的序列化和反序列化是任何非平凡程序的關鍵方面。如果您將某些內容保存到 Python 文件中,如果您讀取配置文件,或者如果您響應 HTTP 請求,您都會進行對象序列化和反序列化。 從某種意義上說,序列化和反序列化是世界上最無聊的事情。誰會在乎所有這些格式和協議?您想持久化或流式傳輸一些 Python 對象,並在以後完整地取回它們。 這是一種在概念層面上看待世界的好方法。但是,在實際層面上,您選擇的序列化方案、格式或協議可能會決定程序運行的速度、安全性、維護狀態的自由度以及與其他系

Python中的數學模塊:統計Python中的數學模塊:統計Mar 09, 2025 am 11:40 AM

Python的statistics模塊提供強大的數據統計分析功能,幫助我們快速理解數據整體特徵,例如生物統計學和商業分析等領域。無需逐個查看數據點,只需查看均值或方差等統計量,即可發現原始數據中可能被忽略的趨勢和特徵,並更輕鬆、有效地比較大型數據集。 本教程將介紹如何計算平均值和衡量數據集的離散程度。除非另有說明,本模塊中的所有函數都支持使用mean()函數計算平均值,而非簡單的求和平均。 也可使用浮點數。 import random import statistics from fracti

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境