Skip to main content
 首页 » 编程设计

ruby之使用 Selenium Webdriver 查找 Web 元素

2025年12月25日33xiaohuochai

我是测试自动化的新手,这是我发现的入门示例。

require 'rubygems' 
require 'selenium-webdriver' 
 
driver = Selenium::WebDriver.for :firefox 
driver.get "http://google.com" 
 
element = driver.find_element :name => "q" 
#element = driver.find_element :xpath => "//*[@id='gbq2']" 
element.send_keys "Cheese!" 
element.submit 
 
puts "Page title is #{driver.title}" 
 
wait = Selenium::WebDriver::Wait.new(:timeout => 10) 
wait.until {driver.title.downcase.start_with? "cheese!"} 
 
puts "Page title is #{driver.title}" 
driver.quit 

从有限的信息中,我知道它正在通过名称查找元素:
1.我怎么知道元素的名字是'q'?
2. 如果我必须通过 X-path 查找元素,为什么它不适用于以下命令?
#element = driver.find_element :xpath => "//*[@id='gbq2']" 

请您参考如下方法:

  1. How do I know that the name of the element is 'q'?


4.html:
<!DOCTYPE html> 
<html> 
<head> 
<title>Testing</title> 
<meta charset="UTF-8"> 
</head> 
<body> 
  <div name="d1">Hello</div> 
  <div name="d2">World</div> 
</body> 
</html> 

ruby 程序:
require 'selenium-webdriver' 
 
driver = Selenium::WebDriver.for :firefox 
driver.get "http:localhost:8080/4.htm" 
 
element = driver.find_element :name => "d1" 
puts element.text 
 
--output:-- 
Hello 

程序如何知道要查找名称为“d1”的元素?因为我写了程序,我决定要找到name属性等于“d1”的元素的文本,所以这就是我在代码中写的。如果程序在该 html 页面上查找名称为 'q' 的元素,您认为会发生什么?

如果你翻看 http://www.google.com的源代码,有一个名为 'q' 的 html 元素,并且编写您发布的 ruby​​ selenium Web 驱动程序示例的人想要获取该元素以对其进行操作。