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

Cách lấy mã HTML của WebElement trong Selenium


Chúng ta có thể lấy mã HTML của một WebElement nhờ Selenium WebDriver. Sử dụng thuộc tính innerHTML để lấy nội dung HTML của phần tử web.

innerHTML là thuộc tính của webelement bằng với nội dung nằm giữa thẻ mở và thẻ đóng. Phương thức getAttribute được dùng cho việc này với innerHTML làm tham số.

Cú pháp

String s = element.getAttribute('innerHTML');

Ví dụ HTML của một phần tử. innerHTML của phần tử sẽ là: You are browsing the best resource for <b>Online Education</b>.

Cách lấy mã HTML của WebElement trong Selenium

Ví dụ

Triển khai mã

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebElement;

public class HtmlCodeElement {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("https://www.tutorialspoint.com/index.htm");
        // Xác định phần tử
        WebElement l = driver.findElement(By.cssSelector("h4"));
        // Lấy innerHTML với getAttribute method
        String s = l.getAttribute("innerHTML");
        System.out.println("HTML code of element: " + s);
        driver.close();
    }
}

Kết quả

Cách lấy mã HTML của WebElement trong Selenium

Mẹo: Ngoài innerHTML, bạn cũng có thể dùng outerHTML để lấy toàn bộ phần tử bao gồm cả thẻ bao quanh.