当前位置: 首页 > 知识库问答 >
问题:

Python Selenium:NoSuChelementException:消息:没有这样的元素:无法定位元素

秦渝
2023-03-14

我是HTML和Selenium的新手,我正在与以下错误作斗争:

引发exception_class(message,screen,stacktrace)selenium.common.exceptions.nosuchelementexception:message:没有这样的元素:找不到元素:{“method”:“xpath”,“selector”:“//[contains(text(),'manage users')]”}*

我尝试了各种各样的属性组合,但都没有成功。我不能直接使用元素的ID,因为它是动态的。下面的代码是我尝试的组合的一部分:

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

driver = webdriver.Chrome()
driver.get('url')

driver.find_element_by_id('j_username').send_keys('my_username')
driver.find_element_by_id('j_password').send_keys('my_password')
driver.find_element_by_id('button.ok').click()

time.sleep(3)

driver.switch_to.frame('portfolio_canvas_area')
driver.switch_to.frame('portfolio_area')

time.sleep(5)

#driver.find_element_by_xpath("/html/body/div/div/form/span/span[1]/span/div/div/table[2]/tbody/tr[3]/td/table/tbody/tr/td[2]/span/span/a")
driver.find_element_by_xpath("//*[contains(text(),'Manage Users')]")
#WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div/div/form/span/span[1]/span/div/div/table[2]/tbody/tr[3]/td/table/tbody/tr/td[2]/span/span/a'))).click()
#WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'//span[text()="Manage Users"]'))).click()
<a href="javascript:action('https://website.com/itim/console/action/Te502a9571b590da5d71c7#W5f82fbdc1b590c3ea782a_treeSel(3)')" id="W5f82fbdc1b590c3ea782a_treeSel(3)" name="W5f82fbdc1b590c3ea782a_treeSel(3)" onclick="if (confirmPageChange()) {saveTaskFormElements();return doSubmit('form', 'W5f82fbdc1b590c3ea782a_treeSel', 'treeSel(3)', 'W5f82fbdc1b590c3ea782a_treeSel(3)', 'treeFunc', 'wh', 'wa'); }" style="color:#000000;font-size:83.3%;font-family:Arial, Helvetica, sans-serif;" taskid="MANAGE_USERS" title="Manage Users">Manage Users</a>

我还附上了一些图片的家长HTML代码从Chrome的检查员与这个问题。我将非常感谢您的帮助,以减轻一些头痛,这已经造成了!谢谢!

共有1个答案

常俊爽
2023-03-14

该消息指示selenium无法定位该元素。

所以也许你可以尝试使用下面的例子,我一直使用它来避免类似这样的错误。

driver.find_element(By.XPATH, "//*[text()='Manage Users']").click()

如果这不起作用,这里有一个清单,你可以尝试

# 1
driver.implicitly_wait(15)

# 2
# make sure the text "Manage Users" don't have space before or after in the HTML code

# 3
# It seems that the "Manage Users" button is a link so you can try the link method
driver.find_element_by_link_text("Manage Users").click()  

# 4
# You can also try with ActionChains, need to import the module first
from selenium.webdriver.common.action_chains import ActionChains  

# then you have try the following
actions = ActionChains(driver)
element = driver.find_element(By.XPATH, "//*[text()='Manage Users']")
actions.move_to_element(element).click(on_element=element).perform()
 类似资料: