如果你看看
source code
class element_to_be_clickable(object):
""" An Expectation for checking an element is visible and enabled such that you can click it."""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
element = visibility_of_element_located(self.locator)(driver)
if element and element.is_enabled():
return element
else:
return False
这个元素可能以前就过时了
if element and element.is_enabled():
位于上一行之后(
visibility_of_element_located
手柄
StaleElementReferenceException
)您可以添加
ignored_exceptions=[StaleElementReferenceException]
减速到
WebDriverWait
解决这个问题
Investment1 = WebDriverWait(driver, 10, ignored_exceptions=[StaleElementReferenceException]).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.menu.menuTopCenter > ul > li:nth-child(3) > a")))
还有几点:
-
有预期情况
frame_to_be_available_and_switch_to_it
处理框架
-
python变量应该都是小写的
-
你有代码重复,你可以用函数代替
options = Options()
options.add_argument("start-maximized")
driver = webdriver.Chrome(options=options,
executable_path=r'C:/Users/SChogle/Downloads/chromedriver.exe')
actions = ActionChains(driver)
driver.get("xxxxxxx")
def do_login():
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe")))
driver.find_element_by_id("Username").send_keys("xxxxx")
driver.find_element_by_id("Password").send_keys("xxxxx")
driver.find_element_by_id("submit_button").click()
driver.switch_to.default_content()
def print_content():
investment = WebDriverWait(driver, 10, ignored_exceptions=[StaleElementReferenceException]).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.menu.menuTopCenter > ul > li:nth-child(3) > a")))
actions.move_to_element(investment).perform()
investment_summary = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"li:nth-child(3) > div > div:nth-child(1) > a"))).click()
imp_prov = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#product-UT td.portfolioProductContractFundHeaderValueRight"))).get_attribute('innerHTML').strip()
print(imp_prov)
do_login()
print_content()
driver.find_element_by_css_selector("a#btnLogoff").click()
do_login()
print_content()
编辑:
根据您添加的stacktrace,异常实际上是打开的
actions.move_to_element(Investment1).perform()
. 它可以通过简单的循环和重试来解决
tries = 0
while tries < 3:
try:
investment = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.menu.menuTopCenter > ul > li:nth-child(3) > a")))
actions.move_to_element(investment).perform()
tries = 3
except StaleElementReferenceException:
tries += 1