代码之家  ›  专栏  ›  技术社区  ›  ryvantage

使用watir提交文本字段

  •  0
  • ryvantage  · 技术社区  · 6 年前

    我正在尝试使用watir以编程方式将文本提交到文本字段中。我正在使用堆栈溢出作为脚本的测试站点。

    我可以参考搜索字段( name='q' )但是提交按钮没有 id name 属性。那么,如何以编程方式引用提交按钮并单击它呢?

    enter image description here

    这是迄今为止我掌握的代码:

    require 'watir'
    require 'pry'
    
    browser = Watir::Browser.new :chrome, headless: true
    
    browser.goto 'https://www.stackoverflow.com'
    browser.text_field(:name, "q").set('user:963076') #the search bar name='q'
    browser.button(#how do I reference the submit button?, '').click
    browser.screenshot.save 'screenafter.png' #the screenshot is so that I know what happened after clicking
    
    browser.close
    browser.quit
    

    直接回答这个问题是很好的,但是一个关于如何自己找到解决问题的解释是更好的,非常感谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rajagopalan    6 年前

    你必须点击这个按钮

    <button type="submit" aria-label="Search..." class="s-btn s-btn__primary btn-topbar-primary js-search-submit"><svg aria-hidden="true" class="svg-icon mx0 iconSearch" width="18" height="18" viewBox="0 0 18 18"><path d="M12.86 11.32L18 16.5 16.5 18l-5.18-5.14v-.35a7 7 0 1 1 1.19-1.19h.35zM7 12A5 5 0 1 0 7 2a5 5 0 0 0 0 10z"></path></svg></button>
    

    按钮的类型属性值为 submit 所以我们可以用它来定位那个按钮,这是代码

    browser.goto 'https://www.stackoverflow.com'
    browser.text_field(name: "q").set('user:963076')
    browser.button(type: 'submit').click