我正在尝试抓取一些数据并找到或创建一个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>'
答案 0 :(得分:1)
@books = @page.xpath(BOOKS_SELECTOR).map do |book|
Book.find_or_create_by(name: book['title'])
end
在节点上使用散列访问器[]
将返回属性的值,而不是Nokogiri::XML::Attr
返回的#attribute
节点。