python selenium 元素在明确存在时向我发出NoSuchElementException

mtb9vblg  于 2022-12-25  发布在  Python
关注(0)|答案(1)|浏览(122)

我试图上传图片在谷歌教学机使用 selenium 在Python中,因为有太多的我手动完成。
当NoSuchElementException明显存在时,我总是得到它。

driver.find_element(By.CSS_SELECTOR, ".add-classes").click()

现在它发生在:因为我已经加了密码。
iframe=驱动程序。查找元素(按.标签名称,“HTML集合[]”)Web驱动程序等待(驱动程序,10).直到(错误代码.框架将可用并切换到它((按.名称,iframe)))Web驱动程序等待(驱动程序,20).直到(错误代码.元素将可单击((按.CSS选择器,“.添加类”))).单击()
我怎样才能让它工作呢?
https://teachablemachine.withgoogle.com/train/image〈〈---这是网页
我试过切换到iframe。

document.getElementsByTagName("iframe")

在页面的控制台中运行这个命令会得到一个可疑的答案:HTMLCollection []。我试着切换到它,你可以看到下面的完整代码:iframe=驱动程序.find_element(通过.标签名称,“HTML集合[]”)
我也试过等待页面加载:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,iframe)))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".add-classes"))).click()

下面是我完整代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import urllib.request
from selenium.webdriver.common.by import By
from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException
import os
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

names1=['Dwayne Johnson', 'Taylor Swift', 'Brad Pitt', 'Jennifer Aniston', 'Kim Kardashian', 'Jessica Alba', 'Tom Cruise', 'Cardi B', 'Tom Hanks', 'Kanye West', 'Justin Bieber', 'Elon Musk', 'George Clooney', 'Emma Watson', 'Will Smith', 'Angelina Jolie', 'Johnny Depp', 'Jennifer Lopez', 'Kirstie Alley', 'Sandra Bullock', 'Julia Roberts', 'Leonardo DiCaprio', 'Steven Spielberg', 'Mel Gibson', 'Ellen DeGeneres', 'Christina Aguilera', 'Natalie Portman', 'Scarlett Johansson', 'Robert Downey Jr.', 'Harrison Ford', 'Robin Williams', 'Bruce Willis', 'Mark Wahlberg', 'Elvis Presley', 'Amy Adams', 'Madonna', 'Kobe Bryant', 'Jim Carrey', 'Drake', 'Rihanna', 'Halle Berry', 'Lady Gaga', 'Michael Jackson', 'Katy Perry', 'Beyoncé', 'Emma Stone', 'Steve Carell', 'Arnold Schwarzenegger']
names2=["방탄 진", "정국","방탄 지민","뷔","슈가","RM","제이홉","conan o'brien","kevin hart","dave chappel","donald trump","joe biden","hilery clinton","j cole","kendrick lamar"]
names=names1+names2

JS_DROP_FILE = """
    var target = arguments[0],
        offsetX = arguments[1],
        offsetY = arguments[2],
        document = target.ownerDocument || document,
        window = document.defaultView || window;

    var input = document.createElement('INPUT');
    input.type = 'file';
    input.onchange = function () {
      var rect = target.getBoundingClientRect(),
          x = rect.left + (offsetX || (rect.width >> 1)),
          y = rect.top + (offsetY || (rect.height >> 1)),
          dataTransfer = { files: this.files };

      ['dragenter', 'dragover', 'drop'].forEach(function (name) {
        var evt = document.createEvent('MouseEvent');
        evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
        evt.dataTransfer = dataTransfer;
        target.dispatchEvent(evt);
      });

      setTimeout(function () { document.body.removeChild(input); }, 25);
    };
    document.body.appendChild(input);
    return input;
"""

def drag_and_drop_file(drop_target, path):
    driver = drop_target.parent
    file_input = driver.execute_script(JS_DROP_FILE, drop_target, 0, 0)
    file_input.send_keys(path)

PATH=R"C:\Users\tmdwn\OneDrive\Documents\웹개발_ai\selenium\chromedriver.exe"
driver=webdriver.Chrome()
driver.get("https://teachablemachine.withgoogle.com/train/image")
driver.implicitly_wait(15)
# ㅅㅂ 있는데 왜 안돼냐?
    # Store iframe web element

iframe=driver.find_element(By.TAG_NAME,"HTMLCollection []")
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,iframe)))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".add-classes"))).click()


for name in names:
    driver.find_element(By.CSS_SELECTOR, ".add-classes").click()
    time.sleep(0.1)
    driver.find_elements(By.CSS_SELECTOR,"button.sample-source-btn").click()

h3s=driver.find_elements(By.TAG_NAME, "h3")
uploads=driver.find_elements(By.ID,"file-input")
for h3, upload, name in zip(h3s, uploads, names):
    h3.click()
    h3.send_keys(f"{name}")
    drag_and_drop_file(upload, R"C:\Users\tmdwn\OneDrive\Documents\웹개발_ai\first_impression\downloads\{}".format(name))
4uqofj5v

4uqofj5v1#

发生错误是因为您没有正确处理任何影子根元素。您需要向下移动到树并使用影子根类逐个处理它们。要了解更多Selenium Shadow Root Handling,请查看。
下面是一个代码示例,我尝试通过点击按钮来添加模型类。希望你能理解如何向下移动元素树。

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(ChromeDriverManager().install())

driver.get("https://teachablemachine.withgoogle.com/train/image")

time.sleep(5)

try:
   element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#tmApp')))
except Exception as e:
   print(e)

shadow_root = element.shadow_root
print(shadow_root)

try:
   root2 = WebDriverWait(driver, 10).until(EC.visibility_of(shadow_root.find_element(By.ID, 'classifier-list')))
except Exception as e:
   print(e)

time.sleep(10) ###PLEASE handle the popup its also inside shadow root.  I did it manually and successfully added the extra class###

shadow_root2 = root2.shadow_root

button = shadow_root2.find_element(By.CSS_SELECTOR, '.add-classes')
button.click()

time.sleep(10)

顺便说一句,我手动关闭了初始弹出窗口。你也应该自动关闭它。顺便说一句,它也在一个影子根目录中

相关问题