在craigslist网站中查找搜索按钮

时间:2015-01-06 16:55:30

标签: html ruby watir watir-webdriver

我想制作一些ruby watirwatir-webdriver代码来搜索房间的craigslist。代码需要找到搜索按钮的HTML元素。在html代码中,它有一个id = searchbtn。当我将此元素视为链接或按钮并使我的代码单击它时,我收到一个错误,即找不到该对象。我不知道如何让我的代码找到这个按钮。请帮我。

url = http://newyork.craigslist.org/search/roo

<button type="submit" id="searchbtn">
<span class="searchicon"></span>
</button>

完整代码 -

require 'watir'
require 'rubygems'
# installed watir-webdriver, but did not require it.

craigslist = "http://newyork.craigslist.org/"
section = "search/roo"
website_section = craigslist + section
search_word = "subway"
html_search_text_box_id = "query"
html_button_id = "searchbtn"
search_page_string = "all new york"

# Create browser.
browser = Watir::Browser.new

puts "connecting to craislist at #{website_section}..."
browser.goto website_section

# Maximize browser
# browser.send_keys :f11

# Type there the text in variable
puts "entering search word = #{search_word}..."
browser.text_field(:name, html_search_text_box_id).set search_word 

#Waiting for search button to appear
Watir::Wait.until { browser.text.include? search_page_string }

puts "clicking on the search button..."
browser.button(:name, html_button_id).click

if browser.text.include? search_page_string
  puts "Test Passed. Found the expected string: #{search_page_string}..."
else
  puts "Test Failed! Could not find the expected string: #{search_page_string}..."
end

puts "End of code..."
browser.close

使用ruby 1.9.3和RVM在linux ubunut 14上运行代码。 ~projectRoot > ruby craigslist.rb

错误 -

/home/john/.rvm/gems/ruby-1.9.3-p551/gems/watir-webdriver-0.6.11/lib/watir-webdriver/elements/element.rb:513:in `assert_exists': unable to locate element, using {:name=>"searchbtn", :tag_name=>"button"} (Watir::Exception::UnknownObjectException)
    from /home/john/.rvm/gems/ruby-1.9.3-p551/gems/watir-webdriver-0.6.11/lib/watir-webdriver/elements/element.rb:119:in `click'
    from craigslist.rb:29:in `<main>'

1 个答案:

答案 0 :(得分:1)

我认为您的问题在第29行:

browser.button(:name, html_button_id).click

当我查看源HTML时,我看到:

<button type="submit" id="searchbtn"><span class="searchicon"></span></button>

这意味着您希望通过:id标识该按钮,而不是:name。试试这个,看看搜索是否正确执行:

browser.button(:id, html_button_id).click