实战练习:用airtest-selenium脚本爬取百度热搜标题

858 阅读2分钟

此文章来源于项目官方公众号:“AirtestProject”
版权声明:允许转载,但转载必须保留原链接;请勿用作商业或者非法用途

1. 前言

很多同学,使用AirtestIDE都是做移动端的测试,其实它还有个隐藏功能,就是做web自动化测试。

搞网页测试,使用AirtestIDE的好处是,能借助selenium的辅助窗,帮助我们快捷地生产web自动化脚本。

selenium_window.gif

这里用到的库叫做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)

climb.gif

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自动化脚本(因为这个练习,不需要生成报告什么的,所以运行命令非常简单):

purepy.gif

4. 小结

那今天的web自动化小练习就到这里啦,如果同学们还有别的想看的自动化脚本,欢迎给我们留言!

PS:Airtest正在参加掘金年度人气团队,辛苦走过路过的朋友,帮忙投个票呗~ rank.juejin.cn/rank/2022/w…


AirtestIDE下载:airtest.netease.com/
Airtest 教程官网:airtest.doc.io.netease.com/
搭建企业私有云服务:airlab.163.com/b2b

官方答疑 Q 群:117973773