Search code examples
ruby-on-railsrubyweb-scrapingmechanize

Is it possible to get a checkbox with Mechanize other than name attribute?


I have been trying scraping with Ruby and Mechanize.
The websites I saw say that the way to get a checkbox and check it is below.

form.checkbox_with(:name => 'name').check

However, the checkbox that I would like to get does not have a name attribute.
Instead, it has a class attribute. Is it possible to do like below or is there any alternative ways to achieve it?

form.checkbox_with(:class => 'class_name').check
form.checkbox_with(:class_name => 'class_name').check

versions
rails: 5.2.4.4
ruby: 2.6.3
mechanize: 2.7.6


Solution

  • according to source code yes.

    def elements_with singular, plural = "#{singular}s"
      class_eval <<-CODE
        def #{plural}_with criteria = {}
          selector = method = nil
          if String === criteria then
            criteria = {:name => criteria}
          else
            criteria = criteria.each_with_object({}) { |(k, v), h|
              case k = k.to_sym
              when :id
                h[:dom_id] = v
              when :class
                h[:dom_class] = v
              when :search, :xpath, :css
      ...
    

    so you can use either

    form.checkbox_with(class: 'class_name').check
    # OR by xpath
    form.checkbox_with(xpath: '//*[@id="someId"]/a[1]').check
    # OR by id
    form.checkbox_with(id: 'someId').check