我對從 Rails 控制臺運行的 Nokogiri 命令和在 Rails Helper 中運行的相同命令中看到的差異感到困惑。
在 Rails 控制臺中,我可以使用以下命令捕獲我想要的資料:
endpoint = "https://basketball-reference.com/leagues/BAA_1947_totals.html"
browser = Watir::Browser.new(:chrome)
browser.goto(endpoint)
@doc_season = Nokogiri::HTML.parse(URI.open("https://basketball-reference.com/leagues/BAA_1947_totals.html"))
player_season_table = @doc_season.css("tbody")
rows = player_season_table.css("tr")
rows.search('.thead').each(&:remove) #THIS WORKED
rows[0].at_css("td").try(:text) # Gets single player name
rows[0].at_css("a").attributes["href"].try(:value) # Gets that player page URL
但是,我的 rails helper 旨在接受這些命令并將它們折疊成方法:
module ScraperHelper
def target_scrape(url)
browser = Watir::Browser.new(:chrome)
browser.goto(url)
doc = Nokogiri::HTML.parse(browser.html)
end
def league_year_prefix(year, league = 'NBA')
# aba_seasons = 1968..1976
baa_seasons = 1947..1949
baa_seasons.include?(year) ? league_year = "BAA_#{year}" : league_year = "#{league}_#{year}"
end
def players_total_of_season(year, league = 'NBA')
# always the latter year of the season, first year is 1947 no quotes
# ABA is 1968 to 1976
league_year = league_year_prefix(year, league)
@doc_season = target_scrape("http://basketball-reference.com/leagues/#{league_year}_totals.html")
end
def gather_players_from_season
player_season_table = @doc_season.css("tbody")
rows = player_season_table.css("tr")
rows.search('.thead').each(&:remove)
puts rows[0].at_css("td").try(:text)
puts rows[0].at_css("a").attributes["href"].try(:value)
end
end
在該模塊上,我嘗試模擬 rails 控制臺命令并將它們分解為模塊。為了測驗它(因為我還沒有構建任何其他功能或視圖),我運行 Rails 控制臺,包含這個幫助程式并運行方法。
但我得到了截然不同的結果。在gather_players_from_season 方法中,我可以看到
player_season_table = @doc_season.css("tbody")
不再抓取作為命令列運行時抓取的相同資料。它也不喜歡這里的屬性方法:
puts rows[0].at_css("a").attributes["href"].try(:value)
所以我的第一個想法是寶石可能有所不同?Watir 正在推出無頭瀏覽器。據我所知,Nokogiri 并沒有引起錯誤。
uj5u.com熱心網友回復:
您首先想到比較 Gem 版本是個好主意,但我注意到兩種代碼解決方案之間的差異:
在 Rails 控制臺中
該代碼使用 URI.open 決議 HTML:Nokogiri::HTML.parse(URI.open("some html"))
在 ScraperHelper 代碼中
該代碼不呼叫 URI.open,Nokogiri::HTML.parse("some html")
也許這種差異會回傳不同的值,并使 ScraperHelper 的其余部分回傳意外的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426337.html
