2015-08-27 81 views
1

我正在實現一個使用Selenium Webdriver和Python來抓取某些網頁的腳本,但是我遇到了一個特殊的問題。在某個時候,我應該使用一個輸入元素併發送一個密鑰,並且在我的本地PC上,腳本運行良好,而在我的服務器上,此元素不可見。 頁面的HTML部分是:元素當前不可見,因此可能不與[Selenium Webdriver + Python]交互

<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) 

但是當我調用該方法明確的元素,劇本趕以下錯誤:

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

我還想說一些另外兩個信息:

  • 只有一個寬度爲301px的元素,如果我嘗試以另一種方式捕獲元素,則會發生此錯誤,所以此元素是唯一的
  • 我的本地PC(腳本工作正常)和我的服務器(有問題)是相同的(python版本,硒版本,瀏覽器版本,操作系統版本)

你知道任何解決方案嗎? 非常感謝

+0

請添加更多信息。你使用的是什麼瀏覽器和webdriver版本?你提供的代碼之前的步驟是什麼?這可能會縮小問題 –

回答

0

我能想到一些值得檢查的事情。您可能需要等待一段時間才能加載頁面。我在測試中遇到了服務器延遲的一些問題,導致某些事情失敗,所以值得檢查。

人們傾向於碰到的其他事物是here。有時當瀏覽器窗口中看不到某個元素時,WebDriver將無法找到它。這裏有一些用於滾動瀏覽器窗口的代碼片段(它們在鏈接中處於Java中,但切換到Python應該相當簡單)。只需在使用find_element_by_xpath()之前刪除該代碼,並且可能會處理該代碼。祝你好運!

+0

不幸的是,我已經驗證了第一點插入一些等待時間,但情況並沒有改變 此外,該元素是可見的從瀏覽器窗口.....我已經嘗試了幾個解決方案其他答案,但他們不工作 – hasmet

+1

出於好奇,是否有一個特定的原因,你爲什麼使用Xpath,而不是'find_element_by_class_name()',你有沒有嘗試通過類名來使用這個元素? – Tyler

+0

在我的情況下,我能夠通過直接使用'find_element_by_class_name()'和http://selenium-python.readthedocs.io/locating-elements.html中的其他人來解決一些問題,但總是有例外...... –

相關問題