python - 当 insideText 包含前导和尾随空白字符时,如何使用 Selenium 和 Python 定位并单击该元素

标签 python selenium

我想找到(并单击)“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&amp;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:

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()
    
  • 使用XPATHtext():

    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()
    
  • 使用XPATHnormalize-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/

相关文章:

python - 定影器替代品?我想知道访问文件的所有进程

java - Selenium 将文本框视为隐藏,即使我可以在浏览器中看到它

selenium - WebDriverError : no such session error using ChromeDriver Chrome through Selenium and Jasmine

java - 在 JavascriptExecutor 中修改 Java 变量

google-chrome - ChromeDriver - 未知错误 : cannot find Chrome binary

python - 将坐标表示转换为邻接列表表示

python - 查询Linux操作系统上某个进程的所有实例的CPU总使用率

Python - Tkinter 中的 Matplotlib : The toolbar pan and zoom doesnt change the cursor

python - 检查字符串是否不是 isdigit() 的更短方法

django - 在 Django 中加载用于 Selenium 测试的装置时出现完整性错误