无法使用硒点击网站

时间:2020-09-03 21:49:43

标签: python html selenium

我以为我理解了这个概念,但我想我不知道。

我想从HTML页面的选项卡列表中单击一个按钮

<div id="subTabs2">
<div id="subTabs">
            
<ul>

<li>
<a class="currentTab" id="sub_tab_timeclock_today" href="?p=timeclock:today">Today</a>
</li>

<li>
<a id="sub_tab_timeclock_my_timesheet" href="?p=timeclock:my_timesheet">My timesheet</a>
</li>

#list continues ....

我想点击“ sub_tab_timeclock_my_timesheet”标签,因此在我的代码中我做了

# some code

driver = webdriver.Chrome(driverPath)

driver.get(url)


username = driver.find_element_by_id("user_handle")
password = driver.find_element_by_id("user_password")

username.send_keys("myUser")
password.send_keys("myPass")

driver.find_element_by_class_name("button1").click()

driver.find_element_by_id("sub_tab_timeclock_my_timesheet").click()

我确实通过了登录页面,但是我不明白为什么我的代码为什么无法单击ID为“ sub_tab_timeclock_my_timesheet”的“我的时间表”标签。

错误消息是:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="sub_tab_timeclock_my_timesheet"]"}
  (Session info: chrome=85.0.4183.83)

我在做什么错了?

谢谢

1 个答案:

答案 0 :(得分:0)

似乎您可能会遇到计时问题。尝试在driver.find_element_by_class_name("button1").click()driver.find_element_by_id("sub_tab_timeclock_my_timesheet").click()之间实施等待。

为此,您需要执行以下操作:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "sub_tab_timeclock_my_timesheet"))
    )
finally:
    driver.quit()

由于我是.NET开发人员,因此不太确定Python代码,但请查看本文以获取语法详细信息: https://selenium-python.readthedocs.io/waits.html