python脚本——selenium自动化执行一些网页上的操作

这篇具有很好参考价值的文章主要介绍了python脚本——selenium自动化执行一些网页上的操作。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、说明

通过python的selenium模块,自动化执行一些网页上的重复的无聊的工作。

二、代码

#! /usr/bin/python3.6
from time import sleep
import csv
import os
import tarfile
import shutil
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.wait import WebDriverWait

usr_name = "****"
usr_pwd = "****"
login_url = '****'
checkid = '*****'
# 左上角coverity cid,用于查询页面是否加载成功
cover_cid_xpath = '//*[@id="table-details-grid"]/div[1]/div[5]/div/div/div[1]/div'
# 分类历史记录xpath,用于查询应用是否成功
change_history_xpath = '//*[@id="source-browser-defect-history"]/div/div/div[2]'

# 选择项目的xpath,搜索cid时的异常处理
exec_xpath = '//*[@id="defect-summaries"]/div[5]'
# chromedriver路径
chrome_path = ""  # /media/vdb1/tools/pytoolpath/chromedriver

# 分析人和评审人
owner_name = ""
work_num = ''
warn_path = '/media/vdb1/workspace/告警'
download_path = '/media/vdb1/download/google'
owner_leader_name = ""
# 存储Excel属性的几个list
err_index_list = []  # cid
err_url_list = []
err_intro_list = []


def move_untar_file():
    files = os.listdir(download_path)
    for file in files:
        if 'result' in file and '.gz' in file:
            src = os.path.join(download_path, file)
            dst = os.path.join(warn_path, file)
            print('src:', src)
            print('dst:', dst)
            shutil.move(src, dst)
            t = tarfile.open(dst)
            t.extractall(path=warn_path)
        elif '2022' in file and '.gz' in file:
            src = os.path.join(download_path, file)
            dst = os.path.join(warn_path, file)
            print('src:', src)
            print('dst:', dst)
            shutil.move(src, dst)
            t = tarfile.open(dst)
            t.extractall(path=warn_path)


# 从表格中导入数据
def import_excel(filepath):
    with open(filepath, newline='') as csvfile:
        reader = csv.reader(csvfile)
        for line in reader:
            err_index_list.append(line[0])
            err_url_list.append(line[1])
            err_intro_list.append(line[2])
    print('open file success!!!')


# 根据工号自动定位告警文件并导入
def find_and_import_excel():
    global work_num
    dirs_hit = []
    files = os.listdir(warn_path)
    for file in files:
        if '2022' in file and '.gz' not in file:
            dirs_hit.append(warn_path + '/' + file)
    for dir in dirs_hit:
        files = os.listdir(dir)
        for file in files:
            owner_path = dir + '/' + file
            if '***_Low' in file and os.path.getsize(owner_path) != 0:
                import_excel(owner_path)


def auto_init():
    global chrome_path, owner_name, owner_leader_name, work_num
    chrome_path = '/media/vdb1/tools/pytoolpath/chromedriver'
    work_num = '****'
    owner_name = '****'
    owner_leader_name = '***'
    move_untar_file()
    find_and_import_excel()


def manual_init():
    global chrome_path, owner_name, owner_leader_name, work_num
    file_path = input('请输入excel文件路径:')
    if len(file_path) == 0:
        work_num = input('请输入工号:')
        if len(work_num) == 0:
            work_num = '****'
        find_and_import_excel()
    else:
        print('excel filepath: ' + file_path)
        import_excel(file_path)

    chrome_path = input('请输入chromedriver文件路径:')
    if len(chrome_path) == 0:
        chrome_path = '/media/vdb1/tools/pytoolpath/chromedriver'
    print('chrome filepath: ' + chrome_path)

    owner_name = input('请输入分析人姓名:')
    if len(owner_name) == 0:
        owner_name = '****'
    print('分析人: ' + owner_name)

    owner_leader_name = input('请输入评审人姓名:')
    if len(owner_leader_name) == 0:
        owner_leader_name = '****'
    print('评审人: ' + owner_leader_name)


# 环境初始化
def init_env():
    global chrome_path, owner_name, owner_leader_name, work_num
    init_mode = input('选择模式:0、手动输入路径  1、自动处理 \n')
    if len(init_mode) == 0 or init_mode != '0':
        auto_init()
    else:
        manual_init()


# 页面登录
def chrome_login():
    chrome_options = webdriver.ChromeOptions()
    driver = webdriver.Chrome(executable_path=chrome_path, chrome_options=chrome_options)
    driver.get(login_url)  # 打开页面
    driver.find_element_by_name('username').send_keys(usr_name)
    driver.find_element_by_name('password').send_keys(usr_pwd)
    driver.find_element_by_id('login-button').click()  # 输入用户名和密码,登录

    # 判断是否登录成功
    WebDriverWait(driver, 20).until(lambda x: x.find_element_by_xpath(cover_cid_xpath).is_displayed())
    while 1:
        index_value = driver.find_elements_by_xpath(cover_cid_xpath)
        if len(index_value) > 0:
            if index_value[0].text == checkid:
                print('login success!!!')
                break
        sleep(1)

    # 打开分类历史记录
    left_cid_xpath = '//*[@id="table-details-grid"]/div[1]/div[5]/div/div'
    driver.find_element_by_xpath(left_cid_xpath).click()
    history_button = '//*[@id="source-browser-defect-history"]/h3/span'
    WebDriverWait(driver, 20).until(lambda x: x.find_element_by_xpath(history_button).is_displayed())
    driver.find_element_by_xpath(history_button).click()
    return driver


def select_project(driver):
    print('项目选择异常处理')
    WebDriverWait(driver, 2).until(lambda x: x.find_element_by_xpath(exec_xpath).is_displayed())
    search_res_lists = driver.find_elements_by_class_name('project-name')
    for search_res in search_res_lists:
        if 'ZXUBP' in search_res.text:
            print(search_res.text)
            search_res.click()
            break
    return driver


# 输入cid并查询
def err_id_search(driver, err_id):
    val_list = []
    time_count = 0
    driver.find_element_by_id('search').send_keys(err_id)
    driver.find_element_by_id('search-button').click()

    # 判断是否加载新的cid成功
    WebDriverWait(driver, 20).until(lambda x: x.find_element_by_xpath(cover_cid_xpath).is_displayed())

    while 1:
        index_value = driver.find_elements_by_xpath(cover_cid_xpath)
        if len(index_value) > 0:
            for val in index_value:
                val_list.append(val.text)
            if str(err_id) in val_list:
                print(str(err_id) + ' load success!!!')
                break
        sleep(1)
        time_count += 1

        # 超时未打开,可能是需要选择项目组
        if time_count > 5:
            try:
                # 判断是否需要选择项目组
                index_value = driver.find_elements_by_class_name('project-name')
                driver = select_project(driver)
                break
            except:
                index_value = driver.find_elements_by_xpath(cover_cid_xpath)
            time_count = 0
    return driver


# 告警处理
def err_handle(driver, err_id, err_intro):
    delay_count = 0
    selected_str = ''
    while 1:
        sleep(1)
        WebDriverWait(driver, 20).until(lambda x: x.find_element_by_name('classification').is_displayed())
        
        # index_value = driver.find_elements_by_xpath('//*[@id="source-browser-defect-history"]/div/div/div[2]/h4/span')
        # if len(index_value) > 0:
        #     print(index_value[0].text)

        try:
            selectTag = Select(driver.find_element_by_name('classification'))  # 分类下拉框
            selected_str = selectTag.first_selected_option.text
        except:
            print('get selected_str failed')

        if selected_str == '未分类' or delay_count >= 10:
            break
        delay_count += 1

    selectTag = Select(driver.find_element_by_name('classification'))
    # selectTag.select_by_value('22')  # 选择误报
    selectTag.select_by_visible_text('误报')

    selectTag = Select(driver.find_element_by_name('severity'))
    selectTag.select_by_visible_text('未指定')  # 严重性选择未指定

    selectTag = Select(driver.find_element_by_name('action'))  # 操作下拉框
    selectTag.select_by_visible_text('忽略')  # 选择忽略

    # 填写处理意见
    err_comment = '【概述】: ' + err_intro
    err_comment = err_comment + '\n【技术分析】:无影响'
    err_comment = err_comment + '\n【技术影响】:无影响'
    err_comment = err_comment + '\n【分析人】:' + owner_name
    err_comment = err_comment + '\n【评审意见】:分析合理'
    err_comment = err_comment + '\n【评审人】:' + owner_leader_name
    driver.find_element_by_id("comment").clear()
    driver.find_element_by_id("comment").send_keys(err_comment)

    # 点击应用
    driver.find_element_by_id('source-browser-defect-triage-apply').click()
    # 查询应用是否成功
    WebDriverWait(driver, 20).until(lambda x: x.find_element_by_xpath(change_history_xpath).is_displayed())
    while 1:
        index_value = driver.find_elements_by_xpath(change_history_xpath)
        if len(index_value) > 0:
            if err_intro in index_value[0].text:
                print(str(err_id) + ' handle success!!!')
                break
        sleep(1)
    return driver


if __name__ == '__main__':
    init_env()
    start_index = 0
    if len(err_index_list) > 0:
        driver = chrome_login()
        for i in range(start_index, len(err_index_list)):
            driver = err_id_search(driver, err_index_list[i])
            driver = err_handle(driver, err_index_list[i], err_intro_list[i])
            print(str(i + 1) + '/' + str(len(err_index_list)) + ':' + err_index_list[i] + ' handle end')
        print('handle end!!')
    else:
        print('handle end!!')

三、用法总结

driver.find_element_by_name
driver.find_element_by_id
driver.find_element_by_xpath
WebDriverWait(driver, 20).until(lambda x: x.find_element_by_xpath(change_history_xpath).is_displayed())

chromdriver下载地址文章来源地址https://www.toymoban.com/news/detail-545482.html

到了这里,关于python脚本——selenium自动化执行一些网页上的操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用Python+selenium实现第一个自动化测试脚本

    这篇文章主要介绍了使用Python+selenium实现第一个自动化测试脚本,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 最近在学web自动化,记录一下学习过程。 此处我选用python3.6+selenium3.0,均用

    2024年02月03日
    浏览(39)
  • Selenium+Python自动化脚本环境搭建的全过程

    * 本文仅介绍环境的搭建,不包含任何脚本编写教程。 先整体说一下需要用到工具 1、Python环境(包括pip) 2、谷歌浏览器(包括对应的WebDriver) 详细步骤: 1、下载安装包 Python Releases for Windows | Python.org   下载完成过后,打开进行安装, 先把下面的add path打钩 ,然后一直下

    2024年01月17日
    浏览(46)
  • Selenium+python怎么搭建自动化测试框架、执行自动化测试用例、生成自动化测试报告、发送测试报告邮件

    本人在网上查找了很多做自动化的教程和实例,偶然的一个机会接触到了selenium,觉得非常好用。后来就在网上查阅各种selenium的教程,但是网上的东西真的是太多了,以至于很多东西参考完后无法系统的学习和应用。 以下整理的只是书中自动化项目的知识内容,介绍怎么搭

    2024年02月05日
    浏览(47)
  • Python+Selenium.webdriver实现WEB端UI自动化测试(实例脚本)

            本篇记录基于Python+Selenium.webdriver实现WEB端UI自动化测试,其中测试用例使用excel维护。为了在实际项目种的扩展应用,建议学习webdriver的元素定位方法,欢迎在评论区沟通讨论。 该示例选取的是登录页不需要输入验证码校验的基础页面(考虑到现在大部分项目都是

    2023年04月08日
    浏览(26)
  • 【苹果】SpringBoot监听Iphone15邮件提醒,Selenium+Python自动化抢购脚本

    Iphone15来了,两年之约你还记得吗? 遂整合之前iphone13及iphone14的相关抢购代码,完成一个 SpringBoot监听Iphone15有货邮件提醒+python自动化脚本 小功能。 后端基于 SpringBoot ,通过 苹果官网进行有货接口调用 ,将 JSON结果解析分析 是否有货,并展示近10条有货记录列;可灵活监听

    2024年02月08日
    浏览(38)
  • Postman-脚本自动化及定时执行脚本(7)

    一.postman脚本自动化 ( 从postman至Newman可以一键执行脚本并生成报告: ) Postman Newman 是一个 CLI(命令行界面)工具,可以使用它来运行 Postman 中的集合(Collection)和环境(Environment)进行自动化测试。postman使用newman插件完成命令执行postman脚本。**(1)newman按装** 1.Newman安

    2024年01月21日
    浏览(33)
  • Selenium如何用于编写自动化测试脚本?

    Selenium如何用于编写自动化测试脚本?它提供了许多测试工具和API,可以与浏览器交互,模拟用户操作,检查网页的各个方面。下面是一些步骤,可以帮助你编写Selenium自动化测试脚本。 1、安装Selenium库和浏览器驱动程序 首先,你需要安装Selenium库和浏览器驱动程序,例如C

    2024年02月09日
    浏览(29)
  • Selenium自动化脚本打包exe文件

    近期由于工作需要写了一个selenium自动化脚本,但是每次运行的时候都要打开Pycharm,因此本人直接使用Python第三方打包库PyInstaller将py文件打包成一个可执行的exe文件,在使用时无需安装Python也可以点击运行。 PyInstaller是一个使用较为简单便捷的打包套件,只需要几行命令即可

    2023年04月08日
    浏览(78)
  • selenium IDE自动化测试脚本的实现

    Selenium IDE   是一个简单的录制回放工具,它可以录制你在浏览器上的操作,回放脚本时,它可以重现录制的动作,就好像你又操作了一遍一样。  selenium IDE是个浏览器插件,你需要在浏览器上安装该插件才能使用。 1.下载chrome或者firefox浏览器的插件。 下载路径:Selenium IDE

    2024年02月03日
    浏览(38)
  • 用selenium IDE手工编写自动化测试脚本

    目录 一、打开selenium IDE插件  二、输入脚本 1.元素定位的验证  console验证Xpath定位 2.元素定位的验证   console验证css定位 selenium IDE属于玩具型自动化测试脚本编写工具,它简单、易上手,对于web自动化测试入门来说,是个非常不错的选择。 使用seleniium IDE插件录制脚本非常容

    2023年04月27日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包