原文地址
记录一下ruby下,selenium-webdriver的使用方法;
最近在用selenium-webdriver抓取数据,但是好像没有找到什么相关的文档,许多东西只能一点点的找,用过后又总是忘记,就写下来,以备查阅;
gem install selenium-webdriver
require 'selenium-webdriver'
# 会打开一个谷歌浏览器
dr = Selenium::WebDriver.for :chrome
# 会在后台打开一个浏览器(headless)
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless')
options.add_argument('--disable-gpu')
dr = Selenium::WebDriver.for :chrome, options: options
dr.window_handles #返回已有的标签页id
dr.window_handle #返回当前标签页id
dr.switch_to.window dr.window_handles[1] #切换到第一个标签页
dr.manage.timeouts.page_load = 30
begin
dr.get 'https://www.example.com'
rescue
retry if dr.find_elements(:css, 'div.content[id="1"]').length < 1
end
page = dr.page_source
class = dr.find_elements(:css, 'div#div-id').attribute('class')
dr.find_elements(:css, 'div#content[id="1"]').click