硒的简单显式等待帮助程序
explicit的Python项目详细描述
helper类使处理selenium显式等待变得更容易,并且 更方便
explicit旨在最小化或消除使用时遇到的常见挫折 动态加载和/或javascript驱动内容的网页上的selenium。通常,开发人员 将尝试使用webdriver的默认find_element_by_<XPATH, CSS, ID, LINK TEXT, ETC>来 找到一个元素,只会遇到各种异常,比如NoSuchelementException, statelementreferenceexception,等等。
Selenium包括几个工具来解决这些限制,最明显的是隐式和显式的 等待。虽然实现隐式等待很容易,但随着 脚本变得更加复杂。显式等待提供了一个更强大的选择,它为 开发人员调整更多的微调控件,但代价是增加了复杂性。
显式包抽象了包装显式等待相关的复杂性。 易于使用的api中常用的功能。举个例子: 您想使用selenium从404页面登录github。你写这样的剧本 在登录凭据中,单击登录按钮:
fromseleniumimportwebdriverdriver=webdriver.Chrome()try:driver.get("https://github.com/this/doesntexist")username_field=driver.find_element_by_id("login_field")username_field.click()username_field.send_keys("my_username")password_field=driver.find_element_by_id("password")password_field.click()password_field.send_keys("my_password")login_button=driver.find_element_by_css_selector("input.btn-primary")login_button.click()finally:driver.quit()
但是,当您运行程序时,会立即出现异常:
(.venv35) ➜ explicit ✗ python example.py Traceback (most recent call last): File "example.py", line 9, in <module> username_field = driver.find_element_by_id("login_field") <...> raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"login_field"}
执行选项的原因可能不太明显,因为 页面加载后再加载。当脚本运行时,它试图立即找到字段 控件后的元素从驱动程序返回。get调用。因为元素不在dom中 然而,硒却抛出了非接触性异常。
explicit通过等待元素加载很容易解决这个问题:
fromexplicitimportwaiterfromexplicitimportID,CSSfromseleniumimportwebdriverdriver=webdriver.Chrome()try:driver.get("https://github.com/this/doesntexist")username_field=waiter.find_element(driver,"login_field",by=ID)username_field.click()username_field.send_keys("my_username")password_field=waiter.find_element(driver,"password",by=ID)password_field.click()password_field.send_keys("my_password")login_button=waiter.find_element(driver,"input.btn-primary",by=CSS)login_button.click()finally:driver.quit()
此外,您还可以使用explicit来处理写入:
fromexplicitimportwaiterfromexplicitimportID,CSSfromseleniumimportwebdriverdriver=webdriver.Chrome()try:driver.get("https://github.com/this/doesntexist")waiter.find_write(driver,"login_field","my_username",by=ID)waiter.find_write(driver,"password","my_password",by=ID,send_enter=True)finally:driver.quit()