元素目前不可见,因此可能无法与[Selenium Webdriver + Python]进行交互

时间:2015-08-27 13:44:41

标签: python selenium selenium-webdriver webdriver

我实现了一个使用Selenium Webdriver和Python来抓取某些网页的脚本,但我遇到了一个特殊的问题。在某个时刻,我应该使用一个输入元素并发送一个密钥,并且在我的本地PC上,脚本运行良好,而在我的服务器上,这个元素结果是不可见的。 页面的HTML部分是:

<div class="class1" style="width: 309px;">
   <div class="sPb-a">
      <div class="class2" style="display: none;" aria-hidden="true">
         www.lol.com
      </div>
   <input class="class3" type="text" dir="ltr" style="width: 301px;"></input>
   </div>
   <div></div>
</div>

在Python中,这是我的代码:

elem = browser.find_element_by_xpath("//input[@style='width: 301px;']")
elem.clear()
time.sleep(1)
elem.send_keys('lol')
time.sleep(1)

但是当我在元素上调用方法clear时,脚本会捕获以下错误:

Element is not currently visible and so may not be interacted with
Stacktrace:
at fxdriver.preconditions.visible (file:///tmp/tmpma637_/extensions/fxdriver@googlecode.com/components/command-processor.js:9982)
at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpma637_/extensions/fxdriver@googlecode.com/components/command-processor.js:12626)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpma637_/extensions/fxdriver@googlecode.com/components/command-processor.js:12643)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpma637_/extensions/fxdriver@googlecode.com/components/command-processor.js:12648)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpma637_/extensions/fxdriver@googlecode.com/components/command-processor.js:12590)

我还想说两个额外的信息:

  • 只有一个宽度为301px的元素,如果我尝试以其他方式捕获元素,也会发生此错误,因此此元素是唯一的
  • 我的本地PC(脚本运行良好)和我的服务器(有问题)之间的配置是相同的(python版本,selenium版本,浏览器版本,操作系统版本)

你知道任何解决方案吗? 非常感谢

1 个答案:

答案 0 :(得分:0)

我可以想到一些值得检查的事情。您可能需要等待一段时间才能加载页面。我的测试服务器延迟有一些问题导致一些事情失败,所以值得检查。

人们倾向于遇到的另一件事是here。有时,当您的浏览器窗口中看不到某个元素时,您的WebDriver无法找到它。这里有一些代码片段用于滚动浏览器窗口(它们在链接中用Java表示,但切换到Python应该相当简单)。在使用find_element_by_xpath()之前删除该代码,这可能会解决它。祝你好运!

相关问题