Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Login Facebook ด้วย Python Selenium

ใช้ Selenium WebDriver ทำ Automation Login Facebook (เพื่อการศึกษา/ทดสอบเท่านั้น)

Prerequisites

  1. pip install selenium
  2. Download GeckoDriver (Firefox) หรือ ChromeDriver (Chrome) ใส่ใน PATH หรือโฟลเดอร์โปรเจกต์

ขั้นตอน

  1. เปิด Browser
  2. ไปที่ facebook.com
  3. หา Element: Email (id="email"), Password (id="pass"), Login Button (id="loginbutton")
  4. Send Keys และ Click

ตัวอย่างโค้ด Python

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

# Setup Firefox
driver = webdriver.Firefox()

try:
    # 1. เปิด Facebook
    driver.get("https://www.facebook.com")
    time.sleep(2)
    
    # 2. หา Elements (Selectors อาจเปลี่ยนได้ ต้อง Check DevTools)
    email = driver.find_element(By.ID, "email")
    password = driver.find_element(By.ID, "pass")
    login_btn = driver.find_element(By.NAME, "login")
    
    # 3. กรอกข้อมูล (ใช้ Environment Variables ใน Production!)
    email.send_keys("your_email@example.com")
    password.send_keys("your_password")
    
    # 4. Login
    login_btn.click()
    
    # รอโหลด
    time.sleep(5)
    print("Login attempted")
    
finally:
    driver.quit()

⚠️ ข้อควรระวัง

  • Security: อย่า Hardcode Password ใช้ Environment Variables
  • ToS: Facebook ห้าม Scraping/Automation ตรวจสอบ Terms of Service
  • Selectors: Facebook เปลี่ยน UI บ่อย ต้อง Update Selectors
  • 2FA: Two-Factor Authentication ต้อง Handle แยก
  • Rate Limiting: อาจถูก Block/Challenge

แนะนำ: ใช้ Official API

สำหรับ Production ใช้ Facebook Graph API แทน (OAuth, Token-based, เข้าถึงข้อมูลได้อย่างถูกต้องและปลอดภัย)