2017-09-13 50 views
0

我試圖將文本發送到google flights出發城市輸入框。我能夠找到它,但是當我嘗試將其發送給send_keys時,我收到錯誤element not visible。硒怎麼可能找到輸入框,但是當我發送密鑰時,它不可用。我沒有這個錯誤,直到我從我的webdriver從firefox切換到chrome。我的代碼如下Selenium發現元素但無法發送文本

import 
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 

class Bot: 

    def __init__(self): 
     # self.browser = webdriver.Firefox(executable_path='./geckodriver') 
     self.browser = webdriver.Chrome('./chromedriver') 
     self.departure_city = "COU" 
     self.destination_city = "HND" 
     self.departure_day = "December 1" 
     self.return_day = "December 10" 
     self.prices = [] 
     self.Run() 

    def Run(self): 
     try: 
      self.SetFlight() 
      self.SetDates() 
      self.FindPrices() 
      self.SendText() 
      time.sleep(10) 
      self.browser.quit() 


     except Exception as ex: 
      print(ex) 
      self.browser.quit() 

    def SetFlight(self): 
     self.browser.get('https://www.google.com/flights/'); 
     departure_take_off_boxes = self.browser.execute_script(
      "return document.querySelectorAll('.EIGTDNC-Kb-f.EIGTDNC-Kb-b')") 
     print(departure_take_off_boxes[0].get_attribute('outerHTML')) 
     print(departure_take_off_boxes[1].get_attribute('outerHTML')) 
     self.browser.implicitly_wait(20) 
     departure_take_off_boxes[0].send_keys(self.departure_city) 
     departure_take_off_boxes[0].send_keys(Keys.RETURN) 
     time.sleep(1) 
     # departure_take_off_boxes[1].send_keys(self.destination_city) 
     # departure_take_off_boxes 

回答

0

分析:

硒可以從頁面發現元素,只意味着該元素具有HTML代碼在網頁源代碼,不等於該元素是頁面上可見。如isPresent()和isDisplay()之間的區別。

對於硒如何確定一個元件是可見的,我knwo一些規則如下:
1.元素大小不爲零
2.元素「顯示器」的CSS值不是「無」

我覺得很奇怪,爲什麼你可以運行firefox驅動程序而不是chrome驅動程序,我想即使是W3C的webdirver規範已經定義了,也許firefox和chrome在他們的webdriver中實現了它們。

回到輸入框不可見的原因,我看着輸入框四周的html代碼,我注意到在輸入框上有一個div層覆蓋,輸入框大小設置爲1x1 in CSS風格。

enter image description here

我試圖隱藏覆蓋DIV層和取消的寬度和高度在CSS設置,在這之後,你能看到它,我可以輸入值。

我不知道T,硒使用以下規則來確定元素可見:

If there is something cover the element, the element will be not visible. 

但是從用戶體驗,用戶無法看到該元素,硒API是儘量最好關閉到用戶體驗。

解決方案:

即使你做的元素達div層,但它的尺寸太小,即使你輸入一些值,你羅納爾多,也很想無法看到您輸入的文本。

這是一個UI設計問題,您需要與開發團隊溝通。

0

嘗試以下:

element = driver.find_element_by_id("id") 
actions = ActionChains(driver) 
actions.move_to_element(element).perform() 
element.Clear() //if needed 
element.SendKeys("sendKeysHere") 

有關詳細信息,請參閱下列文檔的節7.2:http://selenium-python.readthedocs.io/api.html