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

Lấy link website bằng Invoke-WebRequest trong PowerShell

Để lấy các liên kết (hyperlink) trên một trang web bằng PowerShell, ta sử dụng cmdlet Invoke-WebRequest (từ PS 3.0+). Cmdlet này trả về đối tượng `HtmlWebResponseObject` chứa thuộc tính .Links.

Các bước thực hiện

  1. Gọi `Invoke-WebRequest -Uri ` để tải trang.
  2. Truy cập thuộc tính `.Links` (collection các đối tượng Link).
  3. Mở rộng (Expand) thuộc tính href để lấy địa chỉ URL thuần túy.

Ví dụ cơ bản

# Lấy tất cả link từ trang
$req = Invoke-WebRequest -Uri "https://theautomationcode.com"

# Hiển thị toàn bộ đối tượng Link (có InnerHtml, InnerText, href, tagName...)
$req.Links

# Chỉ lấy URL (href)
$req.Links | Select-Object -ExpandProperty href

Đầu ra mẫu

innerHTML : Scripts
innerText : Scripts
outerHTML : Scripts
tagName   : A
href      : https://theautomationcode.com/scripts/

# Sau khi ExpandProperty href:
https://theautomationcode.com/2020/11/
https://theautomationcode.com/author/chiragce17/
https://theautomationcode.com/category/powershell/
https://theautomationcode.com/category/troubleshooting/
...

Nâng cao: Lọc và xử lý Link

# Chỉ lấy link nội bộ (cùng domain)
$baseUrl = "https://theautomationcode.com"
$links = $req.Links | Select-Object -ExpandProperty href | 
         Where-Object { $_ -like "$baseUrl*" } | 
         Sort-Object -Unique

# Chỉ lấy link bên ngoài (external)
$external = $req.Links | Select-Object -ExpandProperty href | 
            Where-Object { $_ -notlike "$baseUrl*" -and $_ -like "http*" } | 
            Sort-Object -Unique

# Xuất ra file
$links | Out-File "internal_links.txt"
$external | Out-File "external_links.txt"

Xử lý lỗi thường gặp

  • SSL/TLS Error: Thêm `[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12` trước khi gọi.
  • Timeout: Dùng tham số `-TimeoutSec 30`.
  • User Agent: Một số trang chặn bot mặc định. Thêm `-UserAgent "Mozilla/5.0 ..."`.
  • JavaScript Rendering: `Invoke-WebRequest` **KHÔNG** thực thi JavaScript. Nếu link được render bởi JS (React, Vue, Angular), cần dùng **Selenium**, **Playwright** hoặc **Puppeteer**.