当元素明显存在时,无法在python中找到元素错误

时间:2018-02-13 09:20:07

标签: python selenium selenium-webdriver selenium-firefoxdriver

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import httpagentparser
driver = webdriver.Firefox()
driver.get("https://www.google.co.in/")
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("user agent online")
elem.send_keys(Keys.RETURN)
ua=driver.find_element_by_class_name("_Mqr")
uaa=httpagentparser.simple_detect(ua)
driver.close()

我甚至尝试过implicit_wait(),但它不起作用,仍然返回未找到的元素exception.please帮助我解决这个问题。

2 个答案:

答案 0 :(得分:0)

尝试显式等待

from selenium import webdriver
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.Firefox()
driver.get("https://www.google.co.in/")
try:
    elem = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.NAME, "q"))
    )
    elem.clear()
    elem.send_keys("user agent online")
    elem.send_keys(Keys.RETURN)
    # your code
finally:
    driver.quit()

答案 1 :(得分:0)

将对您自己脚本的修改签出:

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

driver = webdriver.Firefox()
driver.get("https://www.google.co.in/")
try:
    elem = WebDriverWait(driver, 5).until(expected_conditions.presence_of_element_located((By.NAME, "q")))
    elem.clear()
    elem.send_keys("user agent online")
    print("Found 1st Element")
    elem.send_keys(Keys.RETURN)
    elem = WebDriverWait(driver, 5).until(expected_conditions.presence_of_element_located((By.CLASS_NAME, "_Mqr")))
    print("Found 2nd Element")
finally:
    print("Finishing Up Now")
driver.close()

仅向两个元素添加显式等待条件。

还得到以下输出,显示脚本按预期工作:

Found 1st Element
Found 2nd Element
Finishing Up Now