设置元素等待

1、显式等待

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.support.wait import WebDriverWait

    def text_by_xpath(self,loc):
        '''依据元素返回text信息'''
       # / self.logger.debug(loc)
        for i in range(5):
            try:
                WebDriverWait(self.driver,3,1).until(
                    EC.presence_of_element_located(loc)
                )
                text = self.find_element(*loc).text
                if text!=None:

                    return text
            except Exception as e:
                # self.logger.debug(e)
                pass
        else:
           # self.logger.debug("无内容返回")
            pass

在设置时间内,每隔一段时间对页面进行检测

expected_conditions提供的判断方法:

设置元素等待

 

 

 除了使用该类,还可使用 is_displayed()方法进行判断元素是否可见

from selenium import webdriver
from time import sleep ,ctime

driver = webdriver.Firefox()
driver.get("http://www.baidu.com")

print(ctime())

for i in range(10):
    try:
        el = driver.find_element_by_id("kw1")
        if el.is_displayed():
            break
    except:pass
    sleep(1)

else:
    print("time out")
driver.close()
print(ctime())

2、隐式等待

通过一定时长等待页面上某元素加载完成。如果超出设置的时长还没有被加载,则抛出异常

from selenium import webdriver
from time import sleep ,ctime
from selenium.common.exceptions import  NoSuchElementException

driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")

try:
    print(ctime())
    el = driver.find_element_by_id("kw1").send_keys("111")
except NoSuchElementException as e:
    print(e)
finally:
    driver.close()
    print(ctime())

 

3、sleep休眠方式

 

 

 

 

from selenium import webdriver
from time import sleep ,ctime
from selenium.common.exceptions import NoSuchAttributeException

driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")

try:
print(ctime())
el = driver.find_element_by_id("kw1").send_keys("111")
except NoSuchAttributeException as e
print(e)
finally:
driver.close()
print(ctime())
上一篇:接口加密思路


下一篇:Nginx 服务优化与防盗链