我試圖從網站上刮掉一些內容,並且無法選擇正確的元素。用於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
如果你想你需要提供你刮頁面或至少一些樣本HTML好的答案。此外,嘗試這樣的最佳方式是在irb會話中,您可以隨時查看要掃描的元素,並不斷調整選擇器,直到找到所需的元素。 – Casper
更新與網站刮。我不知道irb是什麼..(交互式ruby會話?從Google搜索中輕鬆設置?) – Steve
IRB包含在Ruby中。嘗試在終端命令行鍵入'irb'。 –