当前位置:网站首页>4.3 模拟浏览器操作和页面等待(显示等待和隐式等待、句柄)
4.3 模拟浏览器操作和页面等待(显示等待和隐式等待、句柄)
2022-06-12 04:56:00 【Triumph19】
模拟浏览器操作
- selenium库提供了模拟浏览器执行一些操作的方法,常用的操作方法如表4-4所示。

提示:swith_to用于切换不同窗口或嵌套页面。例如,使用swith_to.window()切换窗口,参数是选项卡的代号(调用windows_handles属性获取当前开启的所有选项卡,返回选项卡的代号列表);当页面存在iframe标签时,使用swith_to.frame()切换到嵌套页面,参数可以直接是标签的id属性或name属性,也可以是定位的节点;使用swith_to.alert()切换到警告框。
- 在实际的web测试中,会有很多鼠标的操作,不单是只有单击,有时候还要用到右击,双击、拖动等操作。selenium库中的ActionChains类提供了实现这些操作的方法,常用的如表4-5所示。

- 使用ActionChains类初始化对象(如ActionChains(browser)),返回一个ActionChains对象。该对象存储所有用户产生的行为,再通过perform()方法执行这些行为。
SeleniumAPI没有提供某些操作(如下拉滚动条)。在这种情况下,可以直接模拟运行JavaScript,使用execute()方法即可实现。例如,execute_script(“window.scrollTo(0,document.body.scrollHeight)”)实现了将滚动条下拉到页面最底部。
from selenium import webdriver
import time
# 初始化Google Chrome浏览器对象,并赋值给browser
browser = webdriver.Chrome()
# 请求淘宝首页,打开一个浏览器窗口
browser.get('https://www.taobao.com/')
time.sleep(2)
# 通过class 定位“聚划算”节点,并赋值给element
element = browser.find_elements_by_css_selector('.nav-hd li')[2] #因为nav-hd下面有多个li节点,而“聚划算”位于第3个节点
element.click() #单击节点
time.sleep(2) #休眠2s
browser.maximize_window() #窗口最大化
- 注意第9行代码如果写成
element = browser.find_element_by_css_selector('.nav-hd li')[2]
- 会出现报错。

页面等待
- 很多网页采用了Ajax技术,程序无法确定某个节点是否已经完全加载。如果页面实际加载的时间过长,会导致程序使用未加载出来的节点,此时就会抛出NullPointer异常。为了避免这种情况,selenium库提供了显示等待和隐式等待方式。
显示等待
- (1)selenium库提供了WebDriverWait类实现显示等待,WebDriverWait的语法格式如下:
WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions = None)
- 其中driver表示浏览器对象;timeout表示等待时间;poll_frequency表示检查频率,程序会每隔这个时间检查一次,如果满足条件则会执行下一步,如果不满足条件则继续等待,却省时为0.5s;ignore_exceptions表示超市后的异常信息。
- WebDriverWait类须与unit()方法或until_not()方法结合使用。例如,WebDriverWait(driver,10).unit(method,message=“”),表示在10s内,每隔0.5s,调用until里的方法,直到它满足了预期条件,如果时间超过10s,则会抛出异常。
- selenium库的expect_conditions类提供了unit()方法和until_not()方法中预期条件判断的方法,常用的如表4-6所示。

隐式等待
- (2)selenium库直接使用implicitly_wait(timeout)方法实现隐式等待。该方法表示按规定时间内页面的所有元素都加载完了就执行下一步,否则一直等到时间截止,然后再继续下一步。
- 使用selenium模拟浏览器访问淘宝首页(网址https://www.taobao.com/),使用显示等待判断“聚划算”节点是否加载完成,并输出节点文本。

显示等待案例
from selenium import webdriver #导入webdriver模块
from selenium.webdriver.common.by import By #导入By模块
# 导入WebDriverWait模块
from selenium.webdriver.support.ui import WebDriverWait
# 导入excepted_conditions 模块
from selenium.webdriver.support import expected_conditions as EC
# 初始化Google Chrome浏览器对象,并赋值给browser
browser = webdriver.Chrome()
# 请求淘宝首页,打开一个浏览器窗口
browser.get('https://www.taobao.com/')
try:
# 显式等待10s
# 判断class属性值为.nav-hd节点下的所有li节点是否加载完成
element = WebDriverWait(browser,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.nav-hd li')))
print(element[2].text) #输出第三个节点文本,即含有"聚划算"文本的节点
print('资源加载成功')
except:
print('资源加载失败')
finally:
print('清理资源')
browser.close() #关闭浏览器
边栏推荐
- JS to determine whether the tags of multiple classes are empty
- Operation of simulated examination platform for 2022 safety officer-b certificate examination questions
- kali_ Change_ Domestic source
- Enhanced vegetation index evi, NDVI data, NPP data, GPP data, land use data, vegetation type data, rainfall data
- February 19, 2022 [Nolan] Nolan resurrected? Change · Nolan [soul orchid] can be connected to XDD / silly girl
- How to deploy dolphin scheduler 1.3.1 on cdh5
- Asp. Net core EF value conversion
- QT compiling security video monitoring system 44 video uploading
- Musk promotes the development of fascinating new products partners remind important questions
- LabVIEW关于TDMS和Binary存储速度
猜你喜欢
![February 19, 2022 [Nolan] Nolan resurrected? Change · Nolan [soul orchid] can be connected to XDD / silly girl](/img/1a/ab2158a532683632f3a12fe41812f5.jpg)
February 19, 2022 [Nolan] Nolan resurrected? Change · Nolan [soul orchid] can be connected to XDD / silly girl

Map coordinate conversion of Baidu map API

Some problems of silly girl solved

2022“高考记忆” 已打包完成,请查收!

22-2-28 there are many things to do at work today, ETH analysis

Surface net radiation flux data, solar radiation data, rainfall data, air temperature data, sunshine duration, water vapor pressure distribution, wind speed and direction data, surface temperature

Harris corner detection principle-

CCF access control system

One dragon and one knight accompanying programmers are 36 years old

Operation of simulated examination platform for 2022 safety officer-b certificate examination questions
随机推荐
2022“高考记忆” 已打包完成,请查收!
asp. Net core theme Middleware
Jwt Learning and use
JS how to get the date
From science to startup
Qinglong wool - Kaka
L1-066 cat is liquid (5 points)
[backtracking method] queen n problem
QT compiling security video monitoring system 44 video uploading
How to deploy PostgreSQL as a docker container
Musk promotes the development of fascinating new products partners remind important questions
How Bi makes SaaS products have a "sense of security" and "sensitivity" (Part I)
Can‘t find a suitable configuration file in this directory or any parent. Error reporting and resolution
Accumulated temperature spatial distribution data, temperature distribution data, sunshine data, rainfall distribution, solar radiation data, surface runoff data, land use data, NPP data, NDVI data
Spatial distribution data of national multi-year average precipitation 1951-2021, temperature distribution data, evapotranspiration data, evaporation data, solar radiation data, sunshine data and wind
Summary of common interview questions in redis
Advanced MySQL knowledge points (7)
Install pycharm under Kali and create a shortcut access
A complete set of installation procedures (for learning and communication only)
[issue 31] 360 background development practice experience - two rounds of technical aspects