Programming2021-02-102 min read

Cách dùng selenium trong python

Cách dùng selenium trong python.

Nguyen Pham
Xin chào. Mình thích lập trình và công nghệ. Đây là blog mình chia sẻ lại các kiến thức về lập trình, công nghệ.

Selenium là một khuôn khổ di động để thử nghiệm các ứng dụng web. Selenium cung cấp một công cụ phát lại để tạo các bài kiểm tra chức năng mà không cần phải học ngôn ngữ kịch bản kiểm tra.(wikipedia).

Để sử dụng selenium trong python chúng ta cần cài thư viên selenium

pip install selenium

Bây giờ sẽ là ví dụ mình dùng selenium tải ảnh từ facebook:

code
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium import *
import os
import time
import pyautogui
from selenium.webdriver import ActionChains

Đâu tiên chúng ta cần khởi tạo một driver để điều khiển trình duyệt:

code
options = webdriver.ChromeOptions()
options.add_argument("--disable-notifications")
driver = webdriver.Chrome("chromedriver.exe",options=options)

Để mở 1 trang web ta làm như sau:

driver.get("https://facebook.com")

chúng ta có thể thêm time.sleep(1) để chờ nó tải trang facebook rồi thực hiện các thao tác tiếp theo. Như thực hiện DOM

code
    driver.find_element_by_id("email").send_keys("[email protected]")
driver.find_element_by_id("pass").send_keys("*******")
driver.find_element_by_id("u_0_b").click()

Cách chạy mã javascript:

code
driver.execute_script('''
    document.querySelectorAll('[data-pagelet="root"')[3].getElementsByTagName('a')[0].click()
    document.querySelectorAll('[data-pagelet="root"')[3].getElementsByTagName('a')[0].getAttribute('href')''')

cách gửi 1 nút:

code
a = driver.find_element_by_tag_name('body')
a.send_keys(Keys.ARROW_RIGHT)

Cách lấy url hiện tại:

driver.current_url
Tags:#Programming#Python#python#selenium
Cách dùng selenium trong python — vdailyapp Blog