如何使用Selenium WebDriver在嵌套的div中查找元素

时间:2019-01-09 18:00:49

标签: ruby selenium selenium-webdriver

我正在尝试在Google Play商店中找到应用,但无法找到嵌套在其他元素中的元素。我已经看过Java中的一些示例,但不确定我是否正确实现了Ruby。我想选择一个外部div容器,然后在其中选择div,直到获得应用程序标题并打印出来。

我已经阅读了Selenium WebDriver的文档,并试图阅读一些rubygem文档,并且还进行了Google搜索以使用WebDriver查找嵌套的div元素。这是我的第一个Selenium WebDriver项目。

i = 0

app_cards = driver.find_elements(:class_name, "card-content")
app_details = app_cards.find_elements(:class_name, "details")
app_titles = app_details.find_elements(:class_name, "title")

app_titles.each do |app_title|
    puts "App #{i}: " + app_title.attribute("title")
    i = i + 1
end

我希望该脚本将所有应用程序的结果打印在Google Play商店的页面上,然后得到

main.rb:17:in `<main>': undefined method `find_elements' for #<Array:0x00005594417b5f68> (NoMethodError)

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作以打印所有标题

require 'selenium-webdriver'
driver=Selenium::WebDriver.for :firefox
driver.manage.timeouts.implicit_wait = 20
driver.navigate.to('https://play.google.com/store/apps')
driver.find_elements(css: '.details > .title').to_enum.with_index(1) do |element,index|
  puts "App #{index}: " +element.attribute('title')
end