0 0

nokogiri抓取页面报错HTTP redirection loop:5


require 'nokogiri'
require 'open-uri'
url="http://douban.fm"
doc = Nokogiri::HTML(open(url))
doc.xpath('a').each do |link|
     puts link.href
puts link.title
end

报错显示   /open-uri.rb:224:in `open_loop': HTTP redirection loop:

换个地址和标签

url='http://www.zhangxinxu.com/wordpress/?paged=2'
doc = Nokogiri::HTML(open(url))
doc.xpath('h2 a').each do |link|
     puts link.href
puts link.title
end
报错显示 1/gems/nokogiri-1.4.4.1-x86-mingw32/lib/nokogiri/xml/node.rb:158:in `evaluate': Invalid expression: //h2 a (Nokogiri::XML::XPath::SyntaxError)
2011年1月23日 15:07

2个答案 按时间排序 按投票排序

0 0

open-uri不支持cookie,造成重复redirect。用mechanize就行了:

require "rubygems"
require 'mechanize'
agent = Mechanize.new
page = agent.get "http://douban.fm"
doc = Nokogiri::HTML(page.body) 
puts doc.to_html


doc.xpath('h2 a')中,xpath的语法错误。jsntghf的方法可以,或者用css:
doc.css('h2 a').each do |link|
  puts link.href
  puts link.title
end 

2011年1月28日 23:08
0 0

url='http://www.zhangxinxu.com/wordpress/?paged=2' 
doc = Nokogiri::HTML(open(url)) 
doc.xpath('//h2/a').each do |link|
     puts link.content
end 

2011年1月24日 09:27

相关推荐

Global site tag (gtag.js) - Google Analytics