Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Selenium Python-如果找不到元素,请关闭所有内容并重新启动_Python_Selenium_Selenium Webdriver_Element_Restart - Fatal编程技术网

Selenium Python-如果找不到元素,请关闭所有内容并重新启动

Selenium Python-如果找不到元素,请关闭所有内容并重新启动,python,selenium,selenium-webdriver,element,restart,Python,Selenium,Selenium Webdriver,Element,Restart,如果python在页面中找不到该元素,我应该向代码中添加什么来关闭浏览器/程序并重新启动所有内容?您可以使用并等待找到该元素,或者超时: element = driver.find_element_by_id("user_first_name") 另一种选择是将整个打开浏览器、获取页面、查找元素放入一个无休止的while循环中,如果找到元素,您将从该循环中中断: from selenium.common.exceptions import TimeoutException from sele

如果python在页面中找不到该元素,我应该向代码中添加什么来关闭浏览器/程序并重新启动所有内容?

您可以使用并等待找到该元素,或者超时:

element = driver.find_element_by_id("user_first_name")

另一种选择是将整个打开浏览器、获取页面、查找元素放入一个无休止的while循环中,如果找到元素,您将从该循环中
中断

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait

try:
    element = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id('user_first_name'))
    # do smth with the found element
except TimeoutException:
    print "Element Not Found"
    driver.close()

如果您正在等待Ajax调用完成,可以使用
waitForElementPresent(定位器)
。有关处理等待的更多选项,请参阅。

为什么需要重新启动整个过程并检查元素是否存在?它是随机显示的,还是原因是什么?谢谢。谢谢@alecxe程序在循环上运行了n次。当它找不到元素时,它会引发一个错误,整个循环停止。我认为重新加载页面会很好。。而不是重新开始整件事
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

while True:
    driver = webdriver.Firefox()
    driver.get('http://example.com')

    try:
        element = driver.find_element_by_id("user_first_name")
    except NoSuchElementException:
        driver.close()
        continue
    else:
        break

# do smth with the element