脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python Selenium等待元素出现的具体方法

python Selenium等待元素出现的具体方法

2021-12-20 00:28小妮浅浅 Python

在本篇文章里小编给大家分享的是一篇关于python Selenium等待元素出现的具体方法,以后需要的朋友们可以学习参考下。

有一个 Selenium 脚本(Python),它点击回复按钮使anonemail类出现。anonemail 类出现的时间各不相同。因此,我必须使用 sleep 直到元素出现。

我想等到课程出现而不是使用睡眠。我听说过等待命令,但我不知道如何使用它们。

这是我迄今为止所拥有的:

?
1
2
3
browser.find_element_by_css_selector(".reply-button").click()
sleep(5)
email=browser.find_element_by_css_selector(".anonemail").get_attribute("value")

解决:

1、如果验证任何元素的存在,检查元素期望

诱导WebDriverWait设置expected_conditions作为presence_of_element_located()检查元素是否存在于页面的 DOM 上的期望。这并不一定意味着该元素是可见的。所以有效的代码行将是:

?
1
WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".reply-button"))).click()

2、如果提取任何元素的任何属性,检查元素可见的期望

需要诱导WebDriverWait设置。expected_conditions作为visibility_of_element_located(locator)检查元素是否存在于页面的 DOM 上并且可见的期望。可见性意味着元素不仅被显示,而且高度和宽度都大于 0。所以在你的用例中,代码行将是:

?
1
email = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_css"))).get_attribute("value")

3、如果用例要click()在任何元素上调用,检查元素是否可见并启用

要诱导WebDriverWait设置expected_conditions作为element_to_be_clickable()检查元素是否可见并启用以便您可以单击它的期望。所以在你的用例中,代码行将是:

?
1
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".reply-button"))).click()

实例扩展:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import selenium.webdriver.support.expected_conditions as EC
import selenium.webdriver.support.ui as ui
 
 
 
# 一直等待某元素可见,默认超时10秒
def is_visible(locator, timeout=10):
    try:
        ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.XPATH, locator)))
        return True
    except TimeoutException:
        return False
 
# 一直等待某个元素消失,默认超时10秒
def is_not_visible(locator, timeout=10):
    try:
        ui.WebDriverWait(driver, timeout).until_not(EC.visibility_of_element_located((By.XPATH, locator)))
        return True
    except TimeoutException:
        return False

到此这篇关于python Selenium等待元素出现的具体方法的文章就介绍到这了,更多相关python Selenium如何等待元素出现内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.py.cn/jishu/jichu/32546.html

延伸 · 阅读

精彩推荐