我是 Scott,对 python 还是有点陌生,仍在试图弄清楚它是如何工作的......大声笑
我有一个脚本可以登录网站工作,点击一些对象,然后根据点击的设置提取报告
我遇到的问题是有时服务器很忙,所以出现需要不同的时间......有些项目在下拉菜单被激活之前是不可点击的......等等所以我需要脚本来等待每个对象的 xpath 变得可用
我不明白显式等待用法
目前的代码很丑,我对 time.sleep 和其他各种事情的使用不当。
代码包含在下面...但这是我需要等待的示例 我需要插入显式等待,等待元素变为可用
提前感谢您的所有帮助我在本论坛的帮助下解决了脚本中的许多其他问题
#Close City Arrow
print('Close City')
loc_arrow2 = (browser.find_element_by_xpath('//*[@id="rddlLocation_Arrow"]'))
loc_arrow2.click()
time.sleep(2)
#Category Button
print ('Category Button')
CategoryRadioBtn = browser.find_element_by_id('rbnSearchCategory')
CategoryRadioBtn.click()
WebDriverWait(browser,20)
time.sleep(2)
#L1 Set to 3d_blah_blah_blah
print('L1 Set to 3d_blah_blah_blah')
loc_L1 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]'))
loc_L1.click()
time.sleep(2)
loc_L2 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Input"]'))
loc_L2.clear()
loc_L2.send_keys('3')
loc_L2.send_keys(u'\ue007')
让我们以下面的行作为示例来解释 EC(预期条件)。
loc_L1 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]'))
您必须添加以下导入才能使用 EC 处理显式等待。
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
在这里你必须如何编写显式等待
WebDriverWait(driver,waitTimeInSec).until(EC.presence_of_element_located((By.strategy,"xpath_goes_here")))
# Below is the example
loc_L1 = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,'//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]')))
# if you want to wait for the element to be clickable then use below.
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]')))
如果出现ElementNotInteractable
异常,请使用 js 单击,如下所示。
driver.execute_script("arguments[0].click()",loc_L1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句