【问题标题】:Can not find div by class name via Selenium(Python)无法通过 Selenium(Python)按类名找到 div
【发布时间】:2019-07-20 19:02:20
【问题描述】:

我试图在 url http://gridworlds-multiplayer.org/ 中使用类名“rps-wrapper”访问 div 内的“事件”,但是当我使用该函数时出现错误。

    <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')

应该得到类名为rps-wrapper的div,但输出错误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)

【问题讨论】:

  • 你能检查一下是否有 iframe 吗?
  • 可以分享网址吗

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

要在 &lt;div&gt; 中定位 事件,类名称为 rps-wrapper,因为所需元素位于 &lt;frame&gt; 中,因此您必须:

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

    • 使用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
    

在这里你可以找到Ways to deal with #document under iframe的相关讨论

【讨论】:

  • 是否有任何原因我无法使用函数 find_element_by_class_name() 找到 rps_wrapper 对象?我可以确认在执行所述功能时该对象已加载到页面上。
  • @LudwigVonChesterfield Of-coarse 你可以使用 classname 但肯定你需要 WebDriverWait 来切换到 &lt;frame&gt; 首先然后定位元素。
  • 但我没有使用 标签。
  • 除非您切换到&lt;frame&gt;,否则您将无法访问所需的元素。
猜你喜欢
  • 2020-09-26
  • 1970-01-01
  • 2020-03-05
  • 2021-10-18
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多