html - 使用 Ruby 和 Selenium Webdriver find_elements 根据条件选择并单击特定链接

标签 html ruby selenium selenium-webdriver

我对 Ruby 和 Selenium 很陌生。

我正在尝试编写一个脚本来打开一个网页(不是我运行的页面),查看那里的项目列表,然后单击满足特定条件的项目的“详细信息”链接。该页面的精简版是:

<div class="list">

<div class="item">
    <div class="description">Cat</div>
    <div class="price">$3.00</div>
    <div class="detailslink">
        <a href="http://a.htm">Details</a>
    </div>
</div>

<div class="item">
    <div class="description">Dog</div>
    <div class="price">$4.00</div>
    <div class="detailslink">
        <a href="http://b.htm">Details</a>
    </div>
</div>

<div class="item">
    <div class="description">Cat</div>
    <div class="price">$4.00</div>
    <div class="detailslink">
        <a href="http://c.htm">Details</a>
    </div>
</div>

<div class="item">
    <div class="description">Bird</div>
    <div class="price">$3.00</div>
    <div class="detailslink">
        <a href="http://d.htm">Details</a>
    </div>
</div>

我想做的一个例子是点击最昂贵的动物(不是狗)的“详细信息”链接。我猜我会用不包含单词“dog”的 find_elements 创建所有“item”类元素的数组,在该数组中找到最高价格的索引,然后单击相应“detailslink”中的链接",但我不知道如何用 Ruby 写出来。

理想情况下,如果没有满足条件的列表项(“列表”div 中没有“项目”div,或者所有“列表”div 都包含 Cat),它也会每 30 秒刷新一次。这是我目前所拥有的(我知道它遗漏了很多!):

require "selenium-webdriver"
browser = Selenium::WebDriver.for :chrome
browser.get "http://list.htm"
for i in 0..1
    items = browser.find_elements(:class=>"item")
    #Do testing here. If there are non-cats, get the index of the max.
        break
    end
    sleep(30)
    browser.get "http://list.htm"
    redo
end
#find the nth element based on the test above
browser.find_element(:class, "detailslink")[index].click

如有任何帮助,我们将不胜感激!

最佳答案

对于我们这些使用 Ruby 的人来说,gist 中有一张不错的表,用于 find_element 和 find_elements 的使用。

https://gist.github.com/huangzhichong/3284966#file-selenium-webdriver-cheatsheet-md

关于html - 使用 Ruby 和 Selenium Webdriver find_elements 根据条件选择并单击特定链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22918994/

相关文章:

html - 网页设计/CSS : Animated logo with CSS?

javascript - 显示和格式化嵌套的 SVG

jQuery:在页面加载时隐藏图片

html - 使文本显示为绿白色背景

ruby - 如何在 Ruby 中将字符串转换为常量?

ruby-on-rails - 使用设计检查用户是否在登录期间确认

mysql - DatabaseCleaner 不适用于 Capybara 自动化测试

python - 运行使用远程 Webdriver 并连接到 selenium hub 和节点的测试失败

java - 如何在 Selenium Webdriver 中使用 "Upload Image Button"上传文件/照片

java - 无法在 Java 中使用 phantomJS 处理警报