元素不可见异常python

时间:2018-01-10 13:33:28

标签: python selenium

我尝试写一个简短的脚本来搜索报纸网站上的关键词和

'ElementNotVisibleException:消息:元素不可见'被引发。

我无法修复它......

感谢您的帮助

代码:

    import os
    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

    driver = webdriver.Chrome()
    driver.get("https://www.tsa-algerie.com")
    wait = WebDriverWait(driver, 8)
    elem = driver.find_element_by_name("s")
    wait.until(EC.visibility_of_element_located((By.name,"s")))
    elem.send_keys("Algieria")
    elem.send_keys(Keys.RETURN)
    assert "No results found." not in driver.page_source
    driver.close()
    os.system('pause')

2 个答案:

答案 0 :(得分:-1)

你刚刚创建了一个名为wait的变量:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

WebDriverWait(driver, 8).until(EC.visibility_of_element_located((By.NAME, "s")))
elem = driver.find_element_by_name("s")

但是你没有在你的代码中使用它。试试这个:

  

visibility_of_element_located

{{1}}

这样脚本会一直等到'元素出现,然后你会找到这个元素。记住订单。首先,你等一下,然后你可以使用它。

答案 1 :(得分:-1)

This code will help you:

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

driver = webdriver.Chrome()
driver.get("https://www.tsa-algerie.com")
driver.maximize_window()

#To click on Search Icon to open the search box
ele=driver.find_element_by_xpath('//div[@class="template-header__search search__open transition"]/img')
ele.click()

#wait till search text box appear and then enter the desired keyword you want to search
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.NAME, "s")))
elem = driver.find_element_by_name("s")
elem.send_keys("Algieria")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()