web页面加载或跳转时需要执行等待的几种方法:
- 强制等待;
- 隐式等待;
- ‘智能’登场(常用);
具体实现,如下:
# -*- coding:utf-8 -*-
from selenium import webdriver
import time
# 等待
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# `智能`等待
def wait_test(driver):
# 等待条件说明
locator = (By.CSS_SELECTOR, '#xfptxq_B10_01_03 > a > div.layout_img > img')
# 点击事件
element = WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
element.click()
if __name__ == '__main__':
# 驱动Chrome浏览器
driver = webdriver.Chrome('/Users/****/Desktop/git/AI_Lesson/chromedriver')
driver.maximize_window()
driver.get('https://feicuitianyuhqc.fang.com/?ctm=1.nanjing.xf_search.lplist.1')
# 1 强制等待
# time.sleep(10) # 设置等待时间:10s
# 2 隐式等待
# driver.implicitly_wait(10) # 设置最长等待时间:10s
# 3 `智能`等待
wait_test(driver)
# 强制等待
time.sleep(5)
# 关闭浏览器
driver.quit()