1. 程式人生 > >Ruby用百度搜索爬蟲

Ruby用百度搜索爬蟲

https each span 分享圖片 百度 .get get請求 puts 分享

Ruby用百度搜索爬蟲

博主ruby學得斷斷續續,打算寫一個有點用的小程序娛樂一下,打算用ruby通過百度通道爬取網絡信息。

第三方庫準備

  • mechanize:比較方便地處理網絡請求,類似於Python中的requests
  • nokogiri:解析HTML文本,采用的是jquery選擇器

步驟分析

  • 用mechanize創建一個agent對象
  • 我們首先登錄百度主頁
  • 找到百度『搜索』框的表單
  • 填寫表單內容
  • 提交表單(agent用該表單的內容發出submit動作)
  • 分析百度獲得的搜索結果列表
  • 用nokogiri解析HTML文本,提取出我們感興趣的內容

代碼

require ‘mechanize‘
require ‘nokogiri‘ # 百度搜索的關鍵字,可修改 keyword = ‘ruby‘ # 創建一個agent對象 agent = Mechanize.new # 發送get請求獲取頁面 page = agent.get ‘http://www.baidu.com/‘ # 根據名字屬性定位表單 search_form = page.form_with :name => ‘f‘ # 填表,搜索框的name是wd search_form.field_with(:name => "wd").value = keyword # 提交表單 search_results = agent.submit search_form doc = Nokogiri
::HTML(search_results.body) doc.css(‘.c-container > h3 > a‘).each{ |item| puts item.text }

測試結果

技術分享圖片

Ruby用百度搜索爬蟲