其他分享
首页 > 其他分享> > selenium无法click的一个案例分享(2)

selenium无法click的一个案例分享(2)

作者:互联网

案例描述

示例代码1:时间去哪里了

from selenium import webdriver
driver = webdriver.Chrome()
from time import ctime
print(ctime())
driver.get('https://www.healthsmart.com.hk/hs-home/#!/link/home')
print(ctime())

示例代码2:如何有效点击

直接点

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.healthsmart.com.hk/hs-home/#!/link/home')
driver.find_element('id','NavMember').click()   #NavMember 是会员的li的id的值,可以点击的

显式等待点

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get('https://www.healthsmart.com.hk/hs-home/#!/link/home')
ele_huiyuan = 'id','NavMember'
WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(ele_huiyuan)).click()

强制等待点

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get('https://www.healthsmart.com.hk/hs-home/#!/link/home')
ele_huiyuan = 'id','NavMember'
from time import sleep
sleep(1)
WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(ele_huiyuan)).click()

轮询等待原始实现

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get('https://www.healthsmart.com.hk/hs-home/#!/link/home')
from time import time,sleep

start_time = time()   # 定义开始时间
timeout = 5   # 定义超时时间
poll_frequency = 0.5   # 定义轮询时间
end_time = start_time + timeout   # 定义结束时间
while True:
    driver.find_element('id','NavMember').click()   # 点击
    try:
        if driver.find_element('link text','登記會員'):  #看有无这个元素,如果有,跳出循环 ,如果没有,异常了
            driver.find_element('link text', '登記會員').click()
            print('找到了登记会员')
            break  
    except:
        sleep(poll_frequency)  # 等待 轮询时间
        if time()>=end_time:  # 如果超过了结束时间
            print('超时了')
            break   # 也终止

自定义显式等待条件的实现方式

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome()
driver.get('https://www.healthsmart.com.hk/hs-home/#!/link/home')

def find_huiyuan():
    def _predicate(driver):
        try:
            driver.find_element('id','NavMember').click()
            return driver.find_element('link text','登記會員')
        except :
            return False

    return _predicate

WebDriverWait(driver,5,0.5).until(find_huiyuan()).click()

标签:webdriver,selenium,driver,案例,link,home,import,click
来源: https://www.cnblogs.com/wuxianfeng023/p/16615785.html