[英]How to locate and click the element when the innerText contains leading and trailing white-space characters using Selenium and Python
I want to locate (and click) the "Reoni" element, but I do not know what function to use it for我想找到(并单击)“Reoni”元素,但我不知道将它用于什么功能
I tried with我试过
driver.find_element_by_class_name("oe_menu_leaf")
and和
driver.find_element_by_class_name("oe_menu_text")
but then selenium raise an error element cant be located, and I tried但随后硒引发了一个错误元素无法定位,我试过
driver.find_element_by_link_text("Reoni")
This is the element I want to locate:这是我要定位的元素:
<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>
and full html:和完整的html:
If I was not clear enough or if you needed my code, please let me know.如果我不够清楚或者您需要我的代码,请告诉我。
Try something like this:尝试这样的事情:
From Chrome :从铬:
Right click "inspect" on the item you are trying to find the xpath.在您尝试查找 xpath 的项目上右键单击“检查”。
Right click on the highlighted area on the console.右键单击控制台上突出显示的区域。
Go to Copy 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
As the desired element is a dynamic element you need to induce WebDriverWait for the desired element to be clickable and you can use either of the following solutions:由于所需元素是动态元素,您需要引入WebDriverWait以使所需元素可点击,您可以使用以下任一解决方案:
Using CSS_SELECTOR
:使用
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()
Using XPATH
and text()
:使用
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()
Using XPATH
and normalize-space()
:使用
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()
Note : You have to add the following imports :注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
You can find a relevant detailed discussion in:您可以在以下位置找到相关的详细讨论:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.