Using Watir to check for bad links

后端 未结 4 1382
清歌不尽
清歌不尽 2021-01-13 02:32

I have an unordered list of links that I save off to the side, and I want to click each link and make sure it goes to a real page and doesnt 404, 500, etc.

The issue

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 03:17

    My answer is similar idea with the Tin Man's.

    require 'net/http'
    require 'uri'
    
    mylinks = Browser.ul(:id, 'my_ul_id').links
    
    mylinks.each do |link|
      u = URI.parse link.href
      status_code = Net::HTTP.start(u.host,u.port){|http| http.head(u.request_uri).code }
      # testing with rspec
      status_code.should == '200'
    end
    

    if you use Test::Unit for testing framework, you can test like the following, i think

      assert_equal '200',status_code
    

    another sample (including Chuck van der Linden's idea): check status code and log out URLs if the status is not good.

    require 'net/http'
    require 'uri'
    
    mylinks = Browser.ul(:id, 'my_ul_id').links
    
    mylinks.each do |link|
      u = URI.parse link.href
      status_code = Net::HTTP.start(u.host,u.port){|http| http.head(u.request_uri).code }
      unless status_code == '200'
        File.open('error_log.txt','a+'){|file| file.puts "#{link.href} is #{status_code}" }
      end
    end
    

提交回复
热议问题