【问题标题】:unable to locate element error in python when element is clearly present当元素明显存在时无法在 python 中定位元素错误
【发布时间】:2018-02-13 09:20:07
【问题描述】:
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(),但它不起作用并且仍然返回元素未找到异常。请帮助我解决这个问题。

【问题讨论】:

  • 那么你的问题在哪里?
  • 当问题陈述很简单时,很难提供解决方案,"it doesn't work"。请edit您的问题更完整地描述您预期会发生什么以及这与实际结果有何不同。请参阅 How to Ask 以获取有关什么是好的解释的提示。
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。见:How to create a Minimal, Complete, and Verifiable example.
  • 当我使用隐式或显式等待时,我得到一个超时异常
  • 找不到哪个元素?是qMqr 还是两者兼而有之?

标签: python selenium selenium-webdriver selenium-firefoxdriver


【解决方案1】:

尝试显式等待

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

【讨论】:

  • 我试过这段代码,它给了我一个超时异常
  • 时间异常消失了,但我仍然得到 NoSuchElementException
【解决方案2】:

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

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

【讨论】:

  • 我想写一个代码,它必须给最终用户浏览器信息,但是使用 selenium 我们必须指定是使用 chrome 还是 firefox 驱动程序。怎么做?
  • 我想找出他的默认浏览器并只为该浏览器提供驱动程序实例
猜你喜欢
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 2023-04-10
  • 2019-01-09
  • 2015-10-06
  • 2021-05-31
  • 1970-01-01
  • 2019-01-25
相关资源
最近更新 更多