当前位置:网站首页>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() #关闭浏览器
边栏推荐
- Layer sublayer assigns values to the page elements of the parent layer to achieve the effect of transferring values to the page of the parent layer
- 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
- one billion one hundred and eleven million one hundred and eleven thousand one hundred and eleven
- 2022 low voltage electrician test questions and simulation test
- Asp. Net core EF value conversion
- Ubunt 20.04 uses CDROM or ISO as the installation source
- Applet pull-down load refresh onreachbottom
- [C language] realize string interception function
- The third "World War" - chip defense, smokeless battlefield!
- L1-064 AI core code valued at 100 million (20 points)
猜你喜欢

Microsoft announces that it will discontinue support for older versions of visual studio

BI 如何让SaaS产品具有 “安全感”和“敏锐感”(上)

Big manufacturers compete to join rust, performance and safety are the key, and the 2021 rust developer survey report is announced

AI and logistics Patent

Qinglong wool - Kaka

CCF access control system

File contains (regardless of suffix) Apache log remote file contains PHP encapsulated pseudo protocol:

存储器的保护

InnoDB data storage structure – MySQL

Operation of simulated examination platform for 2022 safety officer-b certificate examination questions
随机推荐
JWT learning and use
@What happens if bean and @component are used on the same class?
LabVIEW關於TDMS和Binary存儲速度
【cjson】根节点注意事项
2022-02-28 WPF upper computer 126 understand mqtt
How to quickly reference uview UL in uniapp, and introduce and use uviewui in uni app
National land use data of 30m precision secondary classification
Parallelization of accelerated training tf data. Dataset generator
Detailed explanation of Command Execution Vulnerability
Qinglong wool - Kaka
Simple Tetris
Soil type, soil texture, soil nutrient and change data, soil organic matter, soil pH, soil nitrogen, phosphorus and potassium
IC验证中的force/release 学习整理(6)研究对 wire 类型信号的影响
2022 examination questions and simulation examination for crane driver (limited to bridge crane)
asp. Net core theme Middleware
How Bi makes SaaS products have a "sense of security" and "sensitivity" (Part I)
leetcode 205. Isomorphic Strings
Image processing 13- calculation of integral diagram
Gao Xiang slam14 notes on three Lie groups and Lie algebra
L1-065 "nonsense code" (5 points)