无法通过 Selenium(Python) 按 class 名称找到 div

Can not find div by class name via Selenium(Python)

我正在尝试访问 div 中的 "events",在 url http://gridworlds-multiplayer.org/ 中使用 class 名称 "rps-wrapper",但是当我使用函数我得到一个错误。

    <div class="rps-wrapper">
        <ul id="events"></ul>
        <div class="controls">
            <div class="chat-wrapper">
                <form id="chat-form">
                    <input id="chat" autocomplete="off" title="chat"/>
                    <button id="say">Say</button>
                </form>
            </div>
        </div>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script src="src/client.js"></script>
</body>
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('*the site is here*')
rps_wrapper = driver.find_element_by_class_name('rps-wrapper')

应该得到 div 名称为 class 的 rps-wrapper,但输出错误 elenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".rps-wrapper"} (Session info: chrome=75.0.3770.142)

以class名称rps-wrapper<div>中定位事件所需的元素在 <frame> 中,因此您必须:

  • 诱导 WebDriverWait 以获得所需的 框架并切换到它
  • 诱导 WebDriverWait 使所需的 元素可点击
  • 您可以使用以下任一项

    • 使用CSS_SELECTOR:

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME,"frame")))
      rps_wrapper = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.rps-wrapper>ul#events")))
      
    • 使用XPATH:

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME,"frame")))
      rps_wrapper = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='rps-wrapper']/ul[@id='events']")))
      
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Here you can find a relevant discussion on