2012-05-28 51 views
0

我試圖從網站上刮掉一些內容,並且無法選擇正確的元素。用於X行單元格的表格行的CSS選擇器

我正在使用Nokogiri,並且,據我所知,CSS最好,我試圖用它來選擇我想要的數據。

有一張很大的表格,我不想要這些行,但這些可以改變;例如,它們並不總是第4,5,6,10,14行。

我可以告訴它是否是我想要的行的唯一方法是該行中有TD標記。 什麼是正確的CSS選擇器來做到這一點?

# Search for nodes by css 
    doc.css('#mainContent p table tr').each do |td| 
    throw td 
    end 

編輯:

我想刮boxrec.com/schedule.php。我想要每行匹配的行,但是,這是一個非常大的行,其行數不匹配。不需要每個日期部分的前幾行,包括每隔一行「有變化......」的行,以及在幾天之間間隔行。

SOLUTION:

doc.xpath("//table[@align='center'][not(@id) and not(@class)]/tr").each do |trow| 

    #Try get the date 
    if trow.css('.show_left b').length == 1 
     match_date = trow.css('.show_left b').first.content 

    end 

    if trow.css('td a').length == 2 and trow.css('* > td').length > 10 

     first_boxer_td = trow.css('td:nth-child(5)').first 
     second_boxer_td = trow.css('td:nth-child(5)').first 

     match = { 
     :round => trow.css('td:nth-child(3)').first.content.to_i, 
     :weight => trow.css('td:nth-child(4)').first.content.to_s, 
     :first_boxer_name => first_boxer_td.css('a').first.content.to_s, 
     :first_boxer_link => first_boxer_td.css('a').first.attribute('href').to_s, 
     :second_boxer_name => second_boxer_td.css('a').first.content.to_s, 
     :second_boxer_link => second_boxer_td.css('a').first.attribute('href').to_s, 
     :date => Time.parse(match_date) 
     } 


     #:Weight => trow.css('td:nth-child(4)').to_s 
     #:BoxerA => trow.css('td:nth-child(5)').to_s 
     #:BoxerB => trow.css('td:nth-child(9)').to_s  

     myscrape.push(match) 

    end 
    end 
+0

如果你想你需要提供你刮頁面或至少一些樣本HTML好的答案。此外,嘗試這樣的最佳方式是在irb會話中,您可以隨時查看要掃描的元素,並不斷調整選擇器,直到找到所需的元素。 – Casper

+0

更新與網站刮。我不知道irb是什麼..(交互式ruby會話?從Google搜索中輕鬆設置?) – Steve

+1

IRB包含在Ruby中。嘗試在終端命令行鍵入'irb'。 –

回答

1

你將不能夠告訴td元素tr多少包含,但你可以判斷它是否爲空:

doc.css('#mainContent p table tr:not(:empty)').each do |td| 
    throw td 
end 
+0

它可能會更好,更容易做到這一步,然後。對於每一個tr ...然後確實依靠它的TD,如果有所需的數字「做更多的東西」 – Steve

+0

@Steve:非常。但我不知道Ruby,所以...... – BoltClock

+0

'doc.css'返回一個'NodeSet',它的作用類似於'Array'。將它賦值給一個變量,然後使用'size'將返回找到的元素的數量。從那裏很容易添加條件邏輯。 –

0

你可以這樣做:

tr rows with a 4th td

doc.xpath('//tr/td[4]/..') 

另一種方式與CSS:

doc.css('tr').select{|tr| tr.css('td').length >= 4}