2012-04-22 24 views
6

Với HTML code này:Parsing HTML với Nokogiri trong Ruby

<div class="one"> 
    ..... 
</div> 
<div class="one"> 
    ..... 
</div> 
<div class="one"> 
    ..... 
</div> 
<div class="one"> 
    ..... 
</div> 

Làm thế nào tôi có thể lựa chọn với Nokogiri div thứ hai hoặc thứ ba mà lớp là một trong những?

Trả lời

5
page.css('div.one')[1] # For the second 
page.css('div.one')[2] # For the third 
+2

Nguyên câu trả lời này có CSS ​​'div # one' . Điều đó tìm thấy một div với một * id * của 'one', nhưng HTML có * lớp * của' một'. Đó là lý do tại sao tôi đã tạo CSS 'div.one'. '#' chọn một ID, '.' chọn một lớp. –

7

Bạn có thể sử dụng Ruby để pare xuống một kết quả lớn thiết lập để các mục cụ thể:

page.css('div.one')[1,2] # Two items starting at index 1 (2nd item) 
page.css('div.one')[1..2] # Items with indices between 1 and 2, inclusive 

Bởi vì của Ruby chỉ số bắt đầu từ số không, bạn phải chăm sóc mà mục bạn muốn.

Ngoài ra, bạn có thể sử dụng bộ chọn CSS để tìm ra nth item:

# Second and third items from the set, jQuery-style 
page.css('div.one:eq(2),div.one:eq(3)') 

# Second and third children, CSS3-style 
page.css('div.one:nth-child(2),div.one:nth-child(3)') 

Hoặc bạn có thể sử dụng XPath để có được trận đấu trở lại cụ thể:

# Second and third children 
page.xpath("//div[@class='one'][position()=2 or position()=3]") 

# Second and third items in the result set 
page.xpath("(//div[@class='one'])[position()=2 or position()=3]") 

Với cả CSS và XPath lựa chọn thay thế lưu ý :

  1. Đánh số bắt đầu từ 1, không 0
  2. Bạn có thể sử dụng at_cssat_xpath để lấy lại phần tử khớp đầu tiên, thay vì một NodeSet.

    # A NodeSet with a single element in it: 
    page.css('div.one:eq(2)') 
    
    # The second div element 
    page.at_css('div.one:eq(2)') 
    

Cuối cùng, lưu ý rằng nếu bạn đang lựa chọn một yếu tố duy nhất bởi chỉ số với XPath, bạn có thể sử dụng một định dạng ngắn:

# First div.one seen that is the second child of its parent 
page.at_xpath('//div[@class="one"][2]') 

# Second div.one in the entire document 
page.at_xpath('(//div[@class="one"])[2]') 
+0

Cảm ơn bạn rất nhiều về số lượng ví dụ phong phú. Chúng ta cần thêm câu trả lời như thế này! +1 –

Các vấn đề liên quan