ruby - 处理 Nokogiri 代理上的失败连接

标签 ruby screen-scraping nokogiri

我有以下代码行,用于抓取网站的 html。如您所见,我将代理传入其中

doc = Nokogiri::HTML(open(Scrape.scrape_url + page.to_s, :proxy => 'http://177.19.134.66:8080'))

有时这些代理出现故障,然后我收到错误

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. - connect(2)

我是 ruby​​ 的新手,但我想做的是创建一个代理 IP 地址列表。然后让它尝试使用第一个进行抓取。如果失败,则尝试下一个,直到没有剩下要检查的...

我将如何创建列表然后处理错误?

最佳答案

最简单的是:

['http://localhost:8080','http://localhost:8888','http://localhost:8000'].each do |proxy|
  break if @doc = Nokogiri::HTML(open(Scrape.scrape_url + page.to_s, :proxy => proxy)) rescue nil
end

注意“@doc”,因为“doc”会在循环结束时超出范围。

关于ruby - 处理 Nokogiri 代理上的失败连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11003939/

相关文章:

python - Pandas 抓取的数据在 Pandas 中不起作用

javascript - 解析具有动态内容的网站

ruby-on-rails - ActiveRecord::UnknownAttributeError(未知属性:作者姓名):

ruby - 如何在Ruby中匹配中文单词?

ruby-on-rails - 使用 Mechanize 捕获 POST 请求

ruby - Nokogiri 在 heroku 上产生不同的结果?

ruby-on-rails - 使用“sudo gem install nokogiri”在 Mac 上安装 nokogiri 时出错

ruby-on-rails - rails : How can my app tell if it is running in MRI or JRuby?

ruby-on-rails - Elastic Beanstalk,Bundler 找不到 gem "bundler"的兼容版本

c# - 如何通过代码自动/模拟 Java Applet 的用户导航?