使用 watir 在命令行中显示搜索到的链接 url [英] Show searched links url in command line with watir

查看:24
本文介绍了使用 watir 在命令行中显示搜索到的链接 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Ruby 新手,现在我正在尝试使用 watir.所以我需要在我的命令行中显示所有建立的 url.这是我的代码的开头:

I am new in Ruby and now i'm trying to use watir. So i need to display all founded urls in my command line. Here is the beginning of my code:

browser = Watir::Browser.new 

puts "1. Entering Google"
browser.goto "http://www.google.com"
search_text = "text"
puts " 2. enter "+ search_text +" in the search text field."
browser.text_field(:name, "q").set search_text
puts "3. click the 'Google Search' button."
browser.button(:name, "btnG").click
puts " First 10 links: "

有人可以帮我吗?非常感谢 !;)

Can someone help me? Thanks a lot ! ;)

推荐答案

链接存储在类名为 'r' 的 h3 标签中,因此您可以通过以下方式获取链接元素的集合:

The links are stored inside h3 tag with class name of 'r', so you can get the collection of link elements by:

links = browser.h3s(class: 'r').map(&:link)

url 存储在 href 标签中,因此您可以通过以下方式获取一组 href 值:

The url is stored in the href tag, so you can get an array of href values by:

hrefs = links.map(&:href)

所以要打印:

hrefs.each { |href| puts href }

但其中一些 href 会通过重定向,因此您可能需要这样做:

But some of those hrefs go through a redirect, so you might want to do this:

links.each { |link| puts "#{link.data_href || link.href}" }

这篇关于使用 watir 在命令行中显示搜索到的链接 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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