前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用 Typhoeus 和 Ruby 编写的爬虫程序

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

原创
作者头像
用户614136809
修改2023-10-19 09:57:38
1520
修改2023-10-19 09:57:38
举报
文章被收录于专栏:爬虫0126爬虫0126

以下是一个使用 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 库。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com