我想找到(并单击)“Reoni”元素,但我不知道使用它来实现什么功能
我尝试过
driver.find_element_by_class_name("oe_menu_leaf")
和
driver.find_element_by_class_name("oe_menu_text")
但随后 selenium 引发错误,无法找到元素, 我尝试过
driver.find_element_by_link_text("Reoni")
这是我要定位的元素:
<a href="/web#menu_id=86&action=99" class="oe_menu_leaf" data-menu="86" data-action-model="ir.actions.act_window" data-action-id="99">
<span class="oe_menu_text">
Reoni
</span>
</a>
和完整的 html:
如果我不够清楚或者您需要我的代码,请告诉我。
最佳答案
由于所需的元素是动态元素,因此您需要引发WebDriverWait以使所需的元素可点击,并且您可以使用以下解决方案之一:
使用
CSS_SELECTOR
:WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.oe_menu_leaf[href*='/web#menu_id=']>span.oe_menu_text"))).click()
使用
XPATH
和text()
:WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='oe_menu_leaf' and starts-with(@href,'/web#menu_id=')]/span[@class='oe_menu_text' and text()='Reoni']"))).click()
使用
XPATH
和normalize-space()
:WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='oe_menu_leaf' and contains(@href,'/web#menu_id=')]/span[@class='oe_menu_text' and normalize-space()='Reoni']"))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
引用
您可以在以下位置找到相关的详细讨论:
关于python - 当 insideText 包含前导和尾随空白字符时,如何使用 Selenium 和 Python 定位并单击该元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54080731/