selenium webdriver及wait
- 1 implicitly包打天下
- 2 Linkedin无法登录返回值很乱,怎么破?
1 implicitly包打天下
有了implicitly之后,基本上不再关注网速之类的影响。
self.driver.implicitly_wait(511)
2 Linkedin无法登录返回值很乱,怎么破?
一会儿是拒绝,一会儿是验证码,一会儿是验证图形,一会儿又是直接进public profile。一个字:太乱。login validation逻辑不太好写。
请WebDriverWait出场。
Use the WebDriverWait with a custom condition and a loop. While waiting for the element to be located, periodically send a message to the user.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
class LoginClass:
def click_login(self):
try:
element = WebDriverWait(self.driver, 180, poll_frequency=1, ignored_exceptions=(Exception,)).until(
self.custom_expected_condition((By.XPATH, "//*[@id='global-nav']/div/nav/ul/li[3]/a")))
# If the element is located, proceed to working_screen
element.click()
self.working_screen()
except Exception as e:
print(f"Element not found: {e}")
# Handle the exception as needed (e.g., log, take alternative action, etc.)
def custom_expected_condition(self, locator):
def custom_condition(driver):
try:
element = EC.presence_of_element_located(locator)(driver)
if element:
return element
except Exception as e:
# Handle the exception or send a message to the user
print(f"Waiting for element: {e}")
self.send_user_message("Still waiting for the element...")
return False
return custom_condition
def send_user_message(self, message):
# Implement how to send a message to the user (e.g., print, display in UI, etc.)
print(message)
def working_screen(self):
# Your implementation for the working screen
print("Working screen logic...")
The custom_expected_condition method returns a custom condition function that waits for the presence of the element while periodically sending a message to the user. The poll_frequency parameter sets the interval between checks, and the ignored_exceptions parameter allows the WebDriverWait to ignore specific exceptions during the wait.
等。告诉用户在等。直到进入。