Selenium – Information about web elements

1 min read

Tiếp tục Series về Selenium, trong bài viết này mình sẽ giới thiệu về những thông tin của một element cụ thể mà bạn có thể query ra.

Trước khi đọc bài viết này, để tham khảo các cách lấy element trên web, bạn có thể đọc lại phần trước tại đây!

Is Displayed

Method này được sử dụng để kiểm tra xem element có được hiển trên webpage không. Trả về một Boolean value, trả về True nếu element hiển thị trên giao diện nếu không sẽ trả về false.

let result =  await driver.findElement(By.name("email_input")).isDisplayed();

Is Enabled

Method này được sửa dụng để kiểm tra trạng thái của element là enabled hay disabled trên web page. Method sẽ trả về True nếu element enabled, else returns false.

// Resolves Promise and returns boolean value
let element =  await driver.findElement(By.name("button_input")).isEnabled();

Is Selected

Phương thức này xác định xem Phần tử được tham chiếu có được chọn hay không. Phương pháp này được sử dụng rộng rãi trên các loại element như: Check boxes, radio buttons, input elements, and option.

// Returns true if element ins checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();

Tag Name

Được sử dụng để fetch tagName của element đang được focus.

// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();

Size and Position

Method này được sử dụng để fetch kích thước (dimensions) và toạ độ (coordinates) của element.

Nội dung data được fetched chứa các thông tin sau:

  • X-axis tính từ góc trên bên trái của phần tử
  • Y-axis tính từ góc trên bên trái của phần tử
  • Height (chiều cao) của phần tử
  • Width (chiều rộng) của phần tử
let object = await driver.findElement(By.name('range_input')).getRect();

Get CSS Value

Truy xuất giá trị computed style của thuộc tính (property)

await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
  // Returns background color of the element
  let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');

Text Content

Truy xuất rendered text của element

await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();

Fetching Attributes or Properties

Nói khó hiểu quá, mọi người xem ví dụ bên dưới nhé! ^^

// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));

//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");

Tài liệu tham khảo: https://www.selenium.dev/documentation/webdriver/elements/information/

Avatar photo

Leave a Reply

Your email address will not be published. Required fields are marked *