【发布时间】:2014-07-01 14:21:10
【问题描述】:
我正在使用 Ruby selenium-webdriver gem 创建一个网络抓取/抓取脚本。我正在抓取的页面是通过 AJAX 加载的,并显示某个帐户的信息。如果您在下拉菜单中选择第二个帐号,页面会非常短暂地重定向到另一个 URL 并返回到原始 URL,只是通过 AJAX 加载了不同的信息。我希望能够抓取下拉选项中列出的两个帐号的信息。问题是 Selenium 执行抓取的速度比页面在下拉单击时重定向/重新加载的速度要快,所以我最终没有得到第二个帐户的信息。
def crawl_page
browser = Selenium::WebDriver.for :firefox
browser.manage.timeouts.implicit_wait = 10 # seconds
browser.navigate.to 'http://www.foobar.com'
account_dropdown = Selenium::WebDriver::Support::Select.new(browser.find_element(:id, 'account'))
account_dropdown.options.each do |option|
option.click
wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds
# this wait is not working because option is selected before redirect/refresh:
wait.until { option.selected? }
html = browser.page_source
scrape_page(html)
end
browser.quit
end
我尝试在单击后将sleep(3) 放在行上,但收到以下错误消息:
[remote server] resource://fxdriver/modules/web_element_cache.js:8180:in `fxdriver.cache.getElementAt': Element not found in the cache - perhaps the page has changed since it was looked up (Selenium::WebDriver::Error::StaleElementReferenceError)
我也尝试过使用 Selenium 的显式 wait 代码,但元素的 id 似乎在更新的页面上动态变化,如下所示:
wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds
wait.until { browser.find_element(:id, 'titlexyz').displayed? }
导致出现错误消息,指出它已超时并且找不到元素:
~lib/selenium/webdriver/common/wait.rb:57:in `until': timed out after 10 seconds (Unable to locate element: {"method":"id","selector":"titlexyz"}) (Selenium::WebDriver::Error::TimeOutError)
有什么方法可以让它休眠或等待,而不必在页面上查找特定元素?
【问题讨论】: