使用 Typhoeus 和 Ruby 编写的爬虫程序

以下是一个使用 Typhoeus 和 Ruby 编写的爬虫程序,用于爬取 ,同时使用了 jshk.com.cn/get_proxy 这段代码获取代理:

ruby 复制代码
#!/usr/bin/env ruby

require 'typhoeus'
require 'json'

def get_proxy
  url = "https://www.duoip.cn/get_proxy"
  response = Typhoeus.get(url)
  if response.code == 200
    proxy_json = JSON.parse(response.body)
    proxy_ip = proxy_json['data']['ip']
    proxy_port = proxy_json['data']['port']
    return proxy_ip, proxy_port
  end
rescue Typhoeus::Error => e
  puts "Error: #{e.message}"
  exit(1)
end

def crawl_ebay(proxy_ip, proxy_port)
  url = "https://www.ebay.com"
  headers = {
    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
    'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language' => 'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4',
    'Accept-Encoding' => 'gzip, deflate, br',
    'Referer' => 'https://www.google.com',
    'Connection' => 'keep-alive'
  }

  # 使用 Typhoeus 的 Hydra 对象进行并发请求
  hydra = Typhoeus::Hydra.new

  # 创建一个使用代理的请求
  request = Typhoeus::Request.new(url, headers: headers, proxy: { ip: proxy_ip, port: proxy_port })

  # 使用 Hydra 对象发送请求
  response = hydra.queue(request)

  # 如果请求成功,输出响应体
  if response.code == 200
    puts "Request successful. Response body: #{response.body}"
  # 如果请求失败,输出错误信息
  else
    puts "Request failed. Error: #{response.code}"
  end

  # 关闭 Hydra 对象
  hydra.close
end

# 获取代理
proxy_ip, proxy_port = get_proxy

# 使用获取到的代理进行爬取
crawl_ebay(proxy_ip, proxy_port)

这个程序首先获取一个代理IP和端口,然后使用这个代理进行 ebay.com 的爬取。请注意,这个示例代码可能会随着网站的变化而失效,您可能需要根据实际情况进行调整。同时,请注意,在使用这个程序之前,请确保已经安装了 Typhoeus 库。

相关推荐
朝朝辞暮i7 小时前
C++ 第 23 课:class —— 开始真正进入面向对象
开发语言·c++·算法
小师兄吃牛肉8 小时前
C语言篇:宏
c语言·开发语言
郑同学的笔记8 小时前
【c++随笔28】strcmp 和 memcmp对比
开发语言·c++
言乐69 小时前
Python根据无法识别搜索词找出可能输入内容模型
开发语言·python·django·virtualenv·pygame
weixin_307779139 小时前
有限产能智能排产与动态重排智能体:从需求解构到技术实现
开发语言·人工智能·算法·架构
kakakahahahaha9 小时前
Windows C盘临时文件清理:%temp%、Windows Temp、Prefetch、Windows.old与hiberfil.sys处理指南
c语言·开发语言·windows
朝朝辞暮i9 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法
朝朝辞暮i10 小时前
C++ 第 29 课:回调函数 Callback
开发语言·c++·算法
笨笨饿10 小时前
140_AI新手村MCP与Skills是干嘛的
开发语言·人工智能·python·stm32·单片机·嵌入式硬件·物联网
YOLO数据集集合10 小时前
EvoAgent:面向PR研发治理的自进化Multi-Agent Harness系统
java·开发语言·目标检测·agent·自进化