如何找到并单击元素

时间:2019-01-07 19:38:34

标签: python selenium xpath css-selectors webdriverwait

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

如果我不太清楚或者您需要我的代码,请告诉我。

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

点击按钮

在Chrome中:

右键单击您要查找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

答案 1 :(得分:1)

由于所需元素是动态元素,因此需要诱使 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
    

PS :您可以在Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome

中找到详细的讨论