我试图使用selenium加载等待列表并单击按钮,但似乎找不到元素

2024-10-01 02:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用find_element_by_class_name和link text,这两种方法都会导致nosuchement异常。我只是想为https://v2.waitwhile.com/l/fostersbarbershop/list-view点击这个加入等待列表按钮-非常感谢您的帮助

from selenium import webdriver
import time

PATH = "C:\Python\Pycharm\attempt\Drivers\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://v2.waitwhile.com/l/fostersbarbershop/list-view")

join = False

while not join:

    try:
        joinButton = driver.find_element_by_class_name("disabled")
        print("Button isnt ready yet.")
        time.sleep(2)
        driver.refresh()

    except:
        joinButton = driver.find_element_by_class_name("public-submit-btn")
        print("Join")
        joinButton.click()
        join = True

Tags: namehttpscomviewbydriverelementfind
2条回答

似乎您有同步问题

诱导WebDriverWait()并等待element_to_be_clickable()查找以下ID定位器

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "join-waitlist"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "ww-name"))).send_keys("TestUser")

您需要导入以下库

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

浏览器快照

enter image description here

您尝试自动化的页面是有角度的。通常,在基于脚本的页面中,您下载源代码,页面加载事件被归类为完成,然后运行一些JS脚本来获取/更新页面内容。这些脚本(可能需要几秒钟才能完成)使用您看到的页面更新DOM

相反,selenium只能识别页面是否已加载-selenium将尝试在此readystate点查找这些元素,并且不知道任何正在运行的脚本

在继续之前,您需要等待元素准备就绪

简单的解决方案是在脚本中添加隐式等待。 隐式等待将忽略NoTouchElement异常,直到达到超时

有关等待的更多信息,请参见here

这是要添加的代码行:

driver.implicitly_wait(10)

只要根据需要调整时间就行了

你只需要一次

这是适用于我的代码:

driver = webdriver.Chrome()

driver.get("https://v2.waitwhile.com/l/fostersbarbershop/list-view")
driver.implicitly_wait(10)

join = False
while not join:
    try:
        joinButton = driver.find_element_by_class_name("disabled")
        print("Button isnt ready yet.")
        time.sleep(2)
        driver.refresh()
    except:
        joinButton = driver.find_element_by_class_name("public-submit-btn")
        print("Join")
        joinButton.click()
        join = True

这是最终状态: enter image description here

相关问题 更多 >