面试中,我们经常会遇到“隐藏元素是如何操作的?”带着这个问题我们看下如何操作?
JS
脚本定位到该元素,获取对应的元素对象,再通过removeAttribute
和setAttribute
两个方法完成属性的删除或重新复制操作,使得当前元素处于显示状态即可。<html>
<body>
用户名:<input id="user_name" name="username" type="hidden" /><br>
密码:<input id="pass_word" name="password" type="text" /><br>
<button type="button" name="login" class="login_but" style="display:none;" />
</body>
</html>
#主要是使用JS脚本改变标签的属性值
hi_name = "document.getElementByID('user_name').setAttribute('type', 'text')"
print(driver.execute_script(hi_name ))
driver.find_element_by_id('user_name').send_keys("admin")
print(driver.find_element_by_name("login"))
driver.execute_script("document.getElementsClassName('login_but')[0].removeAttribute('style')")
在自动化测试中,会遇到一些比如环境不稳定、网络不稳定的因素,此时可能需要控制脚本执行速度,那么就需要用到元素等待操作。其实不一定设置等待就好,各有利弊,以下是一些观点仅供参考。
time.sleep(s)
# s表示具体时间,单位为秒。
s
秒后,进行下一步操作。直接使用python
内置的time
模块调用sleep
方法即可。优缺点 | 说明 |
---|---|
优点 | 使用简单,需要用时随时调用即可 |
缺点 | 代码重复率高,且影响代码执行速率。不能精确设置等待时间,过长过段貌似都不合适 |
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://localhost/zentao/user-login.html")
user_name = "$('input:first').val('admin')"
driver.execute_script(user_name)
time.sleep(0.5)
pass_wd = "$(':password').val('ZenTao123456')"
driver.execute_script(pass_wd)
time.sleep(1)
driver.implicitly_wait(s)
# s表示具体时间,单位为秒。
s
时间内,页面加载完成,进行下一步操作,直接通过浏览器驱动对象进行调用。如果在设定的时间之前元素加载完成,则不会继续等待,继续执行下一步。
优缺点 | 说明 |
---|---|
优点 | 对整个脚本的生命周期都起作用,只需要设置一次 |
缺点 | 程序会一直等待加载完成,才会执行下一步,但有时想要的元素加载完了,其他的元素没有加载完,仍要等待全部加载完才进行下一步,不是很灵活,也有点费时间。 |
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://localhost/zentao/user-login.html")
driver.implicitly_wait(10)
user_name = "$('input:first').val('admin')"
driver.execute_script(user_name)
pass_wd = "$(':password').val('ZenTao123456')"
driver.execute_script(pass_wd)
# 导入包
from selenium.webdriver.support.wait import
# 或者
from selenium.webdriver.support.ui import WebDriverWait
lass WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
"""Constructor, takes a WebDriver instance and timeout in seconds.
:Args:
- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
- timeout - Number of seconds before timing out
- poll_frequency - sleep interval between calls
By default, it is 0.5 second.
- ignored_exceptions - iterable structure of exception classes ignored during calls.
By default, it contains NoSuchElementException only.
Example:
from selenium.webdriver.support.ui import WebDriverWait \n
参数 | 说明 |
---|---|
| 驱动器对象 |
| 设置刷新页面的超时时间 |
| 页面刷新频率。默认 |
| 表示忽略异常,如无法找到元素则抛出 |
WebDriverWait
模块有两个方法until
和until_not
: def until(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value is not False."""
screen = None
stacktrace = None
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, 'screen', None)
stacktrace = getattr(exc, 'stacktrace', None)
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message, screen, stacktrace)
def until_not(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value is False."""
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if not value:
return value
except self._ignored_exceptions:
return True
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message)
其中: 1、method:传入对象分两种,一种是匿名函数;另一种是预置条件对象expected_conditions。 2、message:当出现异常时,把异常信息给message; 3、expected_conditions方法通过from selenium.webdriver.support import expected_conditions引入。
WebDriverWait
常用的几个方法如下:
DOM
树中,并不代表元素可见,如果定位到就返回元素;get_ele = WebDriverWait(driver,10).until(expected_conditions.\
presence_of_element_located(By.ID, "xxx"))
DOM
中,并可见,代表元素可显示,宽和高都大于0;get_ele1 = WebDriverWait(driver,10).until(expected_conditions.visibility_of_elemen\
t_located((by=By.ID,value='yyy')))
get_ele2 = WebDriverWait(driver,10).until(expected_conditions.visibility_of(driver\
.find_element(by=By.ID,value='zzz')))
DOM
树中,如果定位到就返回列表:get_ele3 = WebDriverWait(driver,10).until(expected_conditions.presence_of_all_elem\
ents_located(By.CSS_SELECTOR,'.boss')))
get_ele4 = WebDriverWait(driver,10).until(expected_conditions.text_to_be_present_i\
n_element_value(By.CSS_SELECTOR,'#su'))
get_ele5= WebDriverWait(driver,10).until(expected_conditions.text_to_be_present_i\
n_element(By.XPATH,"//#[@id='ul']", u'添加'))
DOM
中或不可见,如果可见,返回False
,否则返回这个元素;get_ele6= WebDriverWait(driver,10).until(expected_conditions.invisibility_of_elem\
ent_located(By.CSS_SELECTOR,'#su'))
enable
(代表可点击);get_ele7= WebDriverWait(driver,10).until(expected_conditions.element_to_be_clicka\
ble(By.CSS_SELECTOR,'#su')).click()
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。