Python 使用Selenium查找嵌套的动态生成元素

Python 使用Selenium查找嵌套的动态生成元素,python,selenium,selenium-webdriver,selenium-chromedriver,Python,Selenium,Selenium Webdriver,Selenium Chromedriver,我正在使用Selenium和Chrome驱动程序,但我无法通过ID找到元素。但是,该元素在浏览器的web检查器中可见。我认为这是因为元素是动态生成的(我在浏览器URL栏中看到相同的URL,但内容是动态变化的) 解决方法是正确理解和驱动程序等待。第一页是登录页,我可以通过以下方式成功通过: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webd

我正在使用Selenium和Chrome驱动程序,但我无法通过ID找到元素。但是,该元素在浏览器的web检查器中可见。我认为这是因为元素是动态生成的(我在浏览器URL栏中看到相同的URL,但内容是动态变化的)

解决方法是正确理解和驱动程序等待。第一页是登录页,我可以通过以下方式成功通过:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
delay = 5

username = driver.find_element_by_name('Username')
password = driver.find_element_by_name('Password')
username.send_keys('my_username')
password.send_keys('my_password')
login = driver.find_element_by_id('login_button')
login.click()
在这一步之后,我可以成功地找到名为say,button_a的元素,单击该元素后,页面生成一个新的按钮say,button_b,我使用wait-for-presence命令

button_a = driver.find_element_by_id('button_a')
button_a.click()
WebDriverWait(driver, delay).until(
    EC.presence_of_element_located(
        driver.find_element_by_id('button_b')))
但是,这会引发典型的异常:

selenium.common.exceptions.NoSuchElementException: Message: no such element:     Unable to locate element: {"method":"id","selector":"button_b"}
似乎驱动程序保留了对旧DOM的引用,而没有跟踪添加到DOM中的新元素,在单击按钮a后页面没有重新加载,但我只是得到了一个经典的旋转轮,客户机正在动态生成新内容。此时,我可以通过右键单击o清楚地看到按钮b id的存在n打开浏览器,然后检查

这可以用硒来解决吗


对不起,我只是web浏览器自动化方面的一个不速之客。

事实上,您出错了,您将查找元素,然后使用wait for WebElement。您应该尝试使用By locator,如下所示:-

button_a = driver.find_element_by_id('button_a')
button_a.click()
button_b = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'button_b')))
驱动程序似乎保留了对旧DOM和 不跟踪添加到DOM中的新元素,该页面不可用 点击按钮后重新加载,但我只是得到了经典的旋转 客户端动态生成新内容的控制盘。 实际上,Selenium会检测页面重新加载、AJAX调用、Javascript执行等对DOM所做的任何更改。 因此,为了测试这一点,如果您有
按钮_a
,请尝试以下操作:

您将得到一个
StaleElementReferenceException
错误(元素不再附加到DOM),这意味着Selenium对该元素所做的任何绑定都将丢失

现在,为了克服您的问题,使用您的示例,您可以使用:

//get the first element, button_a and click it
//going by your example this means you have only one element containing `button`
//in the `id`
driver.find_element_by_xpath(".//*[contains(@id,'button')]").click()
//now, as you say, you will have 2 elements containing `button` in the `id`
//so get all the elements and click on the last one
buttonB = driver.find_elements_by_xpath(".//*[contains(@id,'button')]")
buttonB[len(buttonB)-1].click()
作为说明,我为任何语法错误道歉,如果有的话,因为我不是pythonist

//get the first element, button_a and click it
//going by your example this means you have only one element containing `button`
//in the `id`
driver.find_element_by_xpath(".//*[contains(@id,'button')]").click()
//now, as you say, you will have 2 elements containing `button` in the `id`
//so get all the elements and click on the last one
buttonB = driver.find_elements_by_xpath(".//*[contains(@id,'button')]")
buttonB[len(buttonB)-1].click()