![](/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.