![](/img/trans.png)
[英]How to click on the button when the textContext contains leading and trailing white-space characters?
[英]How to locate and click the element when the innerText contains leading and trailing white-space characters using Selenium and Python
我想找到(并单击)“Reoni”元素,但我不知道将它用于什么功能
我试过
driver.find_element_by_class_name("oe_menu_leaf")
和
driver.find_element_by_class_name("oe_menu_text")
但随后硒引发了一个错误元素无法定位,我试过
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:
如果我不够清楚或者您需要我的代码,请告诉我。
尝试这样的事情:
从铬:
在您尝试查找 xpath 的项目上右键单击“检查”。
右键单击控制台上突出显示的区域。
转到复制 xpath
selectElem=browser.find_element_by_xpath('x-path-here').click()
from bs4 import BeautifulSoup
innerHTML = browser.execute_script("return document.body.innerHTML")
soup = BeautifulSoup(str(innerHTML.encode('utf-8').strip()), 'lxml')
value = soup.find('span', attrs={'class':'fxst-calendarpro fxst-table-s1'}).text
由于所需元素是动态元素,您需要引入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
您可以在以下位置找到相关的详细讨论:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.