AirtestProject 实战练习:用 airtest-selenium 脚本爬取百度热搜标题
此文章来源于项目官方公众号:“AirtestProject”
版权声明:允许转载,但转载必须保留原链接;请勿用作商业或者非法用途
1. 前言
很多同学,使用 AirtestIDE 都是做移动端的测试,其实它还有个隐藏功能,就是做 web 自动化测试。
搞网页测试,使用 AirtestIDE 的好处是,能借助 selenium 的辅助窗,帮助我们快捷地生产 web 自动化脚本。
这里用到的库叫做 airtest-selenium。今天我们就利用 airtest-selenium 来完成一个简单的实操练习:自动爬取百度热搜标题。
2. 爬取标题的脚本
示例为一个简单的纯py
脚本,它的功能是:
- 打开 chrome 浏览器
- 打开百度首页
- 点击 “百度热搜”
- 获取热搜标题并 print 出来
# -*- encoding=utf8 -*-
__author__ = "AirtestProject"
from airtest.core.api import *
auto_setup(__file__)
# 初始化并打开chrome浏览器
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from airtest_selenium.proxy import WebChrome
driver = WebChrome()
driver.implicitly_wait(20)
# 打开百度首页
driver.get("https://www.baidu.com/")
# 点击百度热搜并切换到新标签页
driver.find_element_by_xpath("//*[@id=\"s-hotsearch-wrapper\"]/div/a/div/i").click()
driver.switch_to_new_tab()
# 打印百度热搜榜的标题
for hot in driver.find_elements_by_class_name("c-single-text-ellipsis"):
print(hot.text)
3. 命令行运行 Web 自动化脚本
当然,写好 web 自动化脚本之后,我们其实也不用依赖于 AirtestIDE 来运行的。我们完全可以脱离 IDE。
但相比于在 IDE 上运行 web 脚本,我们只需要在选项设置里面填一下 chrome path 这么简单。脱离 IDE 运行 web 脚本,我们所要准备的工作就多得多的。
1)python 环境准备
首先确保我们有一个可用的 python 环境,其次,需要在环境里面装好第三方库:airtest、airtest-selenium、selenium。
另外还需要注意下,selenium 的版本不能大于 4.0,因为该版本 airtest-selenium 还未兼容。
2)chrome 与 chromedriver 版本对应
另外,我们还需要确保运行环境设置好了版本对应的 chromedriver,否则容易报错:
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 98
Current browser version is 108.0.5359.73 with binary path C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
3)命令行运行
以上 2 个步骤都确认以后,我们可以非常简单的在终端敲命令运行写好的 web 自动化脚本(因为这个练习,不需要生成报告什么的,所以运行命令非常简单):
4. 小结
那今天的 web 自动化小练习就到这里啦,如果同学们还有别的想看的自动化脚本,欢迎给我们留言!
Airtest 官网:https://airtest.netease.com/
Airtest 教程官网:https://airtest.doc.io.netease.com/
搭建企业私有云服务:https://airlab.163.com/b2b
官方答疑 Q 群:117973773
呀~这么认真都看到这里啦,帮忙点击左下角的爱心,给我点个赞支持一下把,灰常感谢~