Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đăng nhập Facebook bằng Python (Selenium)


Ta dùng gói python selenium tự động hóa tương tác với webdriver. Bài này thấy tương tác giữa selenium và đăng nhập Facebook.

Cách tiếp cận

Selenium tự động hóa và điều khiển trình duyệt. Code Python cần cài selenium và driver geckodriver (cho Firefox). Các bước:

Bước 1

Cài selenium:

pip install selenium

Bước 2

Tải geckodriver, đặt cùng thư mục script.

Tạo chương trình import module selenium, mở trang đăng nhập.

Để lấy id ô input, xem source facebook.com tìm id các trường:

Đăng nhập Facebook bằng Python (Selenium)

Code dưới có comment giải thích:

Ví dụ

from selenium import webdriver

# Mở Firefox
browser = webdriver.Firefox()
# Vào Facebook
browser.get("https://www.facebook.com")
# Tìm ô username, password, nút login
uname = browser.find_element_by_id("email")
psword = browser.find_element_by_id("pass")
submit = browser.find_element_by_id("loginbutton")
# Điền thông tin
uname.send_keys("hello@gmail.com")
psword.send_keys("thepassword")
# Tự động click Login
submit.click()

Kết quả:

Đăng nhập Facebook bằng Python (Selenium)

Với thông tin đúng, đăng nhập tự động. Tính năng Selenium cho phép điều này.

Lưu ý: Facebook hiện nay có bảo vệ chống bot phức tạp, cách này có thể không còn hoạt động. Chỉ mang tính minh họa.