Đang cố gắng parse HTML với Ruby? Nhiệm vụ này hơi khó nếu thiếu công cụ phù hợp.
May mắn thay, Ruby có thư viện tuyệt vời Nokogiri - biến parse HTML thành "bánh vẽ"!
Cài Đặt Nokogiri
gem install nokogiri
Nếu lỗi cài đặt, thử:
gem install nokogiri -- --use-system-libraries
Trích Xuất Title
Script cơ bản parse HTML snippet:
require 'nokogiri' html = "<title>test</title><body>actual content here...</body>" parsed_data = Nokogiri::HTML.parse(html) puts parsed_data.title # => "test"
Parse trực tiếp từ URL:
require 'open-uri'
Nokogiri::HTML.parse(open('https://example.com')).title
Trích Xuất Link (Anchor Tags)
Lấy tất cả link từ trang:
document = Nokogiri::HTML.parse(open('https://example.com'))
document.class # Nokogiri::HTML::Document
Truy vấn 2 cách: XPath hoặc CSS selectors.
Dùng XPath
tags = document.xpath("//a")
Lọc tất cả thẻ a (chứa link). Kết quả: mảng Nokogiri::XML::Element.
Lấy URL và text:
tags.each do |tag|
puts "#{tag[:href]}\t#{tag.text}"
end
Lấy hình ảnh (thẻ img, attribute src):
tags = document.xpath("//img")
images_urls = tags.map { |t| t[:src] }
Dùng DevTools trình duyệt để tìm selector/attribute đúng.
Dùng CSS Selectors Với Nokogiri
Thay xpath bằng css:
headers = document.css("h1")
paragraphs = document.css("p")
Lưu ý:
at_csstrả về phần tử đầu tiên khớp,csstrả về tất cả phần tử khớp.
CSS selector phổ biến hơn XPath, đa số dev quen thuộc hơn.
Tóm Tắt
Tài liệu Nokogiri: rubydoc.info
Có thể bạn thích: Ruby string format