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 ý :
- Đánh số bắt đầu từ 1, không 0
Bạn có thể sử dụng at_css
và at_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]')
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. –