ProxyForge Download

Ruby Nokogiri Scraping with Proxies: HTTP Clients and Proxy Rotation

Introduction

Web scraping is a powerful tool for gathering data from websites. However, it often requires navigating around anti-scraping measures like IP blocking and CAPTCHAs. Proxies are one of the key tools in the web scraper’s arsenal, allowing you to distribute your requests across multiple IPs and avoid getting blocked.

Ruby, with its rich ecosystem of libraries, is a popular choice for web scraping. Nokogiri is a well-regarded HTML/XML parser, but it doesn't fetch web pages on its own. You need an HTTP client to make requests. In this guide, we'll explore various Ruby HTTP clients that support proxies and how to integrate them with Nokogiri for efficient web scraping.

Setting Up Proxies in Ruby

When using proxies, you’ll often encounter two scenarios: single proxy usage and proxy rotation. Let's dive into the different ways you can set up proxies in Ruby.

1. Using Net::HTTP

Net::HTTP is a built-in library that provides an interface for making HTTP requests. It supports proxy settings directly in its constructor.

require 'net/http'
require 'uri'

def fetch_with_net_http(url, proxy_host, proxy_port, user = nil, pass = nil)
  uri = URI(url)
  http = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, user, pass)
  response = http.start { |h| h.get(uri.request_uri) }
  response
end

# Usage example:
response = fetch_with_net_http('http://example.com', 'proxy.example.com', 8080, 'user', 'pass')
puts response.body

2. Using open-uri

open-uri is another built-in library that simplifies HTTP requests and supports proxies through an option.

require 'open-uri'

def fetch_with_open_uri(url, proxy_host, proxy_port)
  uri = URI(url)
  options = { proxy: "http://#{proxy_host}:#{proxy_port}" }
  response = open(uri, options).read
  response
end

# Usage example:
response = fetch_with_open_uri('http://example.com', 'proxy.example.com', 8080)
puts response

3. Using Faraday

Faraday is a powerful HTTP client that supports many features like middleware and proxy settings.

require 'faraday'

def fetch_with_faraday(url, proxy_host, proxy_port, user = nil, pass = nil)
  conn = Faraday.new(url, proxy: { uri: "http://#{user}:#{pass}@#{proxy_host}:#{proxy_port}" })
  response = conn.get
  response.body
end

# Usage example:
response = fetch_with_faraday('http://example.com', 'proxy.example.com', 8080, 'user', 'pass')
puts response.body

4. Using Typhoeus

Typhoeus is a HTTP client built on top of libcurl and supports proxy settings along with parallel requests.

require 'typhoeus'

def fetch_with_typhoeus(url, proxy_host, proxy_port, user = nil, pass = nil)
  options = {
    proxyurl: "http://#{proxy_host}:#{proxy_port}",
    proxyuserpwd: "#{user}:#{pass}"
  }
  response = Typhoeus.get(url, options)
  response.body
end

# Usage example:
response = fetch_with_typhoeus('http://example.com', 'proxy.example.com', 8080, 'user', 'pass')
puts response.body

Proxy Rotation Strategies

Proxy rotation is crucial for maintaining a low risk of getting blocked by websites. Here are some strategies you can implement.

Basic Proxy Rotation with Rescue Blocks

The simplest way to rotate proxies is to maintain an array of proxy details and swap them when an error occurs, such as Errno::ECONNREFUSED.

require 'faraday'

proxies = [
  { host: 'proxy1.example.com', port: 8080, user: 'user1', pass: 'pass1' },
  { host: 'proxy2.example.com', port: 8080, user: 'user2', pass: 'pass2' }
]

def fetch_with_rotation(url, proxies)
  shuffled_proxies = proxies.shuffle
  shuffled_proxies.each do |proxy|
    begin
      conn = Faraday.new(url, proxy: { uri: "http://#{proxy[:user]}:#{proxy[:pass]}@#{proxy[:host]}:#{proxy[:port]}" })
      response = conn.get
      return response.body
    rescue Errno::ECONNREFUSED => e
      puts "Connection refused with #{proxy}. Trying next proxy..."
    end
  end
  raise "All proxies failed"
end

# Usage example:
response = fetch_with_rotation('http://example.com', proxies)
puts response.body

Parallel Proxy Requests with Typhoeus

Typhoeus supports making parallel requests, which can be useful for handling multiple proxies simultaneously.

require 'typhoeus'

proxies = [
  { host: 'proxy1.example.com', port: 8080, user: 'user1', pass: 'pass1' },
  { host: 'proxy2.example.com', port: 8080, user: 'user2', pass: 'pass2' }
]

def fetch_parallel(url, proxies)
  hydra = Typhoeus::Hydra.new
  requests = []

  proxies.each do |proxy|
    options = {
      proxyurl: "http://#{proxy[:host]}:#{proxy[:port]}",
      proxyuserpwd: "#{proxy[:user]}:#{proxy[:pass]}"
    }
    request = Typhoeus::Request.new(url, options)
    requests << request
  end

  hydra.queue(*requests)
  hydra.run

  responses = requests.map(&:response).compact.map(&:body)
  responses.first || raise("All proxy requests failed")
end

# Usage example:
response = fetch_parallel('http://example.com', proxies)
puts response.body

Parsing HTML with Nokogiri

Once you have fetched the web page content, you can use Nokogiri to parse and extract data.

require 'nokogiri'

def parse_html(html_content)
  doc = Nokogiri::HTML(html_content)
  titles = doc.css('.product-title').map(&:text)
  titles
end

# Usage example:
html_content = fetch_with_faraday('http://example.com', 'proxy.example.com', 8080, 'user', 'pass')
titles = parse_html(html_content)
puts titles

Full Example: Using Faraday for Proxy Requests and Nokogiri for Parsing

Here’s a complete example that combines fetching with Faraday and parsing with Nokogiri.

require 'faraday'
require 'nokogiri'

proxies = [
  { host: 'proxy1.example.com', port: 8080, user: 'user1', pass: 'pass1' },
  { host: 'proxy2.example.com', port: 8080, user: 'user2', pass: 'pass2' }
]

def fetch_with_rotation(url, proxies)
  shuffled_proxies = proxies.shuffle
  shuffled_proxies.each do |proxy|
    begin
      conn = Faraday.new(url, proxy: { uri: "http://#{proxy[:user]}:#{proxy[:pass]}@#{proxy[:host]}:#{proxy[:port]}" })
      response = conn.get
      return response.body
    rescue Errno::ECONNREFUSED => e
      puts "Connection refused with #{proxy}. Trying next proxy..."
    end
  end
  raise "All proxies failed"
end

def parse_html(html_content)
  doc = Nokogiri::HTML(html_content)
  titles = doc.css('.product-title').map(&:text)
  titles
end

# Usage example:
url = 'http://example.com'
html_content = fetch_with_rotation(url, proxies)
titles = parse_html(html_content)
puts titles

Conclusion

In this guide, we explored various ways to use Ruby and Nokogiri for web scraping with proxy support. We looked at different HTTP clients like Net::HTTP, open-uri, Faraday, and Typhoeus, each with its own set of features and use cases.

Proxy rotation is a crucial part of effective web scraping, helping you distribute your requests across multiple IPs and avoid getting blocked. We covered basic rotation strategies and parallel fetching using Typhoeus.

If you're looking for an easy way to manage and test proxies locally, consider ProxyForge. It auto-tests and rotates proxies on your machine without the need for a subscription: https://proxyforge.dev/#download

For professional or managed proxy services, Bright Data and SmartProxy are reliable providers that offer residential proxies suitable for production use.

Remember, always respect the terms of service of websites you're scraping and ensure your activities comply with legal requirements.

Free proxies break. ProxyForge doesn't.

The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.

Download ProxyForge free →