使用 Watir 检查坏链接 [英] Using Watir to check for bad links

查看:32
本文介绍了使用 Watir 检查坏链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无序列表的链接,我保存在旁边,我想点击每个链接并确保它转到真实页面,而不是 404、500 等.

问题是我不知道该怎么做.有没有我可以检查的对象,它会给我 http 状态代码或任何东西?

mylinks = Browser.ul(:id, 'my_ul_id').linksmylinks.each 做 |link|链接.点击# 需要在这里检查 200 状态或其他东西!如何?浏览器.back结尾

解决方案

我的回答与铁皮人的想法相似.

<前>需要'net/http'需要'uri'mylinks = Browser.ul(:id, 'my_ul_id').linksmylinks.each 做 |link|u = URI.parse link.hrefstatus_code = Net::HTTP.start(u.host,u.port){|http|http.head(u.request_uri).code }# 使用 rspec 进行测试status_code.should == '200'结尾

如果你使用 Test::Unit 作为测试框架,你可以像下面这样进行测试,我认为

<前>assert_equal '200',status_code

<小时>

另一个示例(包括 Chuck van der Linden 的想法):检查状态代码并在状态不佳时注销 URL.

<前>需要'net/http'需要'uri'mylinks = Browser.ul(:id, 'my_ul_id').linksmylinks.each 做 |link|u = URI.parse link.hrefstatus_code = Net::HTTP.start(u.host,u.port){|http|http.head(u.request_uri).code }除非 status_code == '200'File.open('error_log.txt','a+'){|file|file.puts "#{link.href} 是 #{status_code}" }结尾结尾

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 is that I do not know how to do it. Is there some object I can inspect which will give me the http status code or anything?

mylinks = Browser.ul(:id, 'my_ul_id').links

mylinks.each do |link|
  link.click

  # need to check for a 200 status or something here! how?

  Browser.back
end

解决方案

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

这篇关于使用 Watir 检查坏链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆