簡體   English   中英

機械化不會影響到站點

[英]Mechanize won't conect to site

歡迎,我遇到了問題,geme機械化將無法連接到站點。 寶石已安裝。 碼:

require 'mechanize'

agent = Mechanize.new
main_page = agent.get 'https://imbd.com'
main_page.link_with(text: "Top 250").click
rows = list_page.root.css(".lister-list tr")

puts rows.size

這是一個錯誤:

C:/Ruby/lib/ruby/2.2.0/net/http.rb:879:in `initialize': 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) for "imbd.com" port 80 (Errno::ETIMEDOUT)
    from C:/Ruby/lib/ruby/2.2.0/net/http.rb:879:in `open'
    from C:/Ruby/lib/ruby/2.2.0/net/http.rb:879:in `block in connect'
    from C:/Ruby/lib/ruby/2.2.0/timeout.rb:73:in `timeout'
    from C:/Ruby/lib/ruby/2.2.0/net/http.rb:878:in `connect'
    from C:/Ruby/lib/ruby/2.2.0/net/http.rb:863:in `do_start'
    from C:/Ruby/lib/ruby/2.2.0/net/http.rb:858:in `start'
    from C:/Ruby/lib/ruby/gems/2.2.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:700:in `start'
    from C:/Ruby/lib/ruby/gems/2.2.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:631:in `connection_for'
    from C:/Ruby/lib/ruby/gems/2.2.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:994:in `request'
    from C:/Ruby/lib/ruby/gems/2.2.0/gems/mechanize-2.7.4/lib/mechanize/http/agent.rb:267:in `fetch'
    from C:/Ruby/lib/ruby/gems/2.2.0/gems/mechanize-2.7.4/lib/mechanize.rb:464:in `get'
    from C:/Ruby/Workspace/imbd.rb:4:in `<main>'

有人知道怎么了嗎? 謝謝!

看完imdb后,我看到他們正在運行大量的javascript,由於無法解析js並無法理解傳入的響應,因此會使Mechanize跳閘。 如果您要抓取內容或自動瀏覽,我建議使用Capybara而不是Mechanize。 將Capybara與類似Poltergeist之類的東西(您需要使用這種方法安裝phantom.js)相結合,要比Mechanize更好,並且可以自動與加載大量js的頁面進行交互。

我添加了一種可能為您解決錯誤的方法。 如果這行得通,那是因為Mechanize試圖在完成js腳本之前獲取頁面,因此無法獲取有效數據。

編輯:

  agent = Mechanize.new
  agent.read_timeout=3  #set the agent time out
  begin
  main_page = agent.get 'https://imbd.com'
  main_page.link_with(text: "Top 250").click
  rows = list_page.root.css(".lister-list tr")
  rescue Timeout::Error 
    puts "Timeout!"
    puts "read_timeout attribute is set to #{agent.read_timeout}s" if !agent.read_timeout.nil?
  end

機械化確實不支持javascript,但問題是您試圖訪問的網站不存在。 您嘗試訪問www.imbd.com而不是www.imdb.com 因此,錯誤消息是准確的。

和FWIW, IMDB不想讓您抓取他們的網站:

機械手和屏幕抓取:未經以下明確的書面同意,您不得在本網站上使用數據挖掘,機械手,屏幕抓取或類似的數據收集和提取工具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM