问题
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 ! ;)
回答1:
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)
The url is stored in the href tag, so you can get an array of href values by:
hrefs = links.map(&:href)
So to print this:
hrefs.each { |href| puts 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}" }
回答2:
Here's a generic approach to pulling links from a specific page element. It specifies the container element (i.e. a div
tag), collects the links in that container, and prints the text
for each link (or each href
-- depending on what's specified in the block):
require 'watir-webdriver'
b = Watir::Browser.new
b.goto('http://www.iana.org/domains/reserved')
b.div(class: "navigation").links.each { |link| puts link.text}
b.div(class: "navigation").links.each { |link| puts link.href}
来源:https://stackoverflow.com/questions/34949773/show-searched-links-url-in-command-line-with-watir