TypeError:无法将Nokogiri :: XML :: Attr转换为字符串

时间:2016-05-11 21:14:51

标签: ruby-on-rails xpath nokogiri

我正在尝试抓取一些数据并找到或创建一个Rails对象,代码如下:

@books = @page.xpath(BOOKS_SELECTOR).map { |book| Book.find_or_create_by(name: book.attribute('title'))}

但是,当此代码运行时,我收到此错误:

  1) Error:
ScrapeHelperTest#test_scrape_page_test:
TypeError: can't cast Nokogiri::XML::Attr to string
    app/helpers/scrape_helper.rb:25:in `block in scrape'
    app/helpers/scrape_helper.rb:25:in `map'
    app/helpers/scrape_helper.rb:25:in `scrape'
    test/helpers/scrape_helper_test.rb:11:in `block in <class:ScrapeHelperTest>'

1 个答案:

答案 0 :(得分:1)

@books = @page.xpath(BOOKS_SELECTOR).map do |book| 
  Book.find_or_create_by(name: book['title'])
end

在节点上使用散列访问器[]将返回属性的值,而不是Nokogiri::XML::Attr返回的#attribute节点。