Selenium番外篇文本查找、元素高亮、截图、无头运行

Selenium根据文本查找元素

sql 复制代码
```python
def find_element_with_text(self, loc, attribute, text):
        try:
            WebDriverWait(self.driver, 5).until(
                EC.all_of(EC.text_to_be_present_in_element_attribute(loc, attribute, text)))
            element = self.driver.find_element(*loc)
            if isinstance(element, NoneType):
                logging.error("%s 页面中未能找到 %s 元素" % (self, loc))
            else:
                return element

        except Exception as e:
            self.save_picture('出现异常')
            logging.info(e)

        else:
            return element
复制代码
## Selenium 截图

​

```python
def save_picture(self, pic_name):
        try:
            projectPath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

            pic_dir = projectPath + "\\pictures\\" + time.strftime('%Y-%m-%d')
            # logging.info('图片文件夹路径为:'+pic_dir)
            if os.path.exists(pic_dir):
                # logging.info('图片文件夹已存在路径为:' + pic_dir)

                pass
            else:
                # logging.info('图片文件夹路径不存在创建文件夹' )

                os.makedirs(pic_dir)
            pic_name = pic_dir + '\\' + pic_name + time.strftime('%Y-%m-%d %H_%M_%S') + '.png'
            # logging.info('图片文件路径为:'+pic_name)

            self.driver.get_screenshot_as_file(pic_name)
            allure.attach.file(pic_name, attachment_type=allure.attachment_type.PNG)
        except Exception as e:
            traceback.print_stack()
            logging.info(e)
        else:
            logging.info('截图路径:%s' % pic_name)
            return pic_name

selenium高亮元素

python 复制代码
def set_high_light_elment(self, element):
        """高亮web元素。

        Args:
           element:
                WebElement:web元素
        """
        element_style=element.get_attribute('style')
        self.mark_dom_text(element_style,200,200)

        script = '''
        arguments[0].setAttribute('style','background: #e0e7c8; border:2px solid red;');{}'''.format(element_style)
        logging.info('用js设置定位元素高亮...')
        # 调用js将传入参数的页面元素对象的背景颜色和边框颜色分别设定为黄色和红色
        # self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", element, "background: yellow; border:2px solid red;")
        try:
            # 方案一
            # self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", element, "background: yellow; border:2px solid red;{}".format(element_style))
            # 方案二
            self.driver.execute_script(script,element)
        except Exception as e:
            traceback.print_stack()
            traceback.print_exception(e)

​Selenium 无头模式运行

def test_chrome_options_headless(self):

复制代码
chrome_options = webdriver.ChromeOptions()
# 无头模式
# chrome_options.add_argument("--headless")
# 设置窗口大小
# chrome_options.add_argument("--window-size=800,600")
# 窗口最大化
chrome_options.add_argument("--start-maximized")
# 设置用户数据
chrome_options.add_argument("user-data-dir=/path/to/your/custom/profile")

driver = webdriver.Chrome(options=chrome_options)

driver.get('https://www.baidu.com')
time.sleep(5)
driver.find_element(By.XPATH, '''//*[@id="kw"]''').send_keys('Chrome')
driver.find_element(By.XPATH, '''//*[@id="su"]''').click()
assert 'Chrome' in driver.page_source

相关推荐
xkxnq1 分钟前
第八阶段:工程化、质量管控与高级拓展(130天),Vue端到端测试:Cypress自动化测试(登录流程+表单提交+页面跳转)
前端·vue.js·flutter
小雨下雨的雨3 分钟前
基于鸿蒙PC Electron框架技术完成的五子棋游戏 - 技术实现详解
前端·javascript·游戏·华为·electron·鸿蒙
cheems95274 分钟前
[开发日记]Spring Boot + MyBatis-Plus 抽奖系统开发复盘:从奖品创建、活动校验到前端圈选人员失效的一次完整排障
前端·spring boot·mybatis
老毛肚5 分钟前
jeecgboot vue API 拆分02
前端·javascript·vue.js
赵谨言11 分钟前
基于C#的在线编码与自动化测试全栈Web平台的设计与实现
开发语言·前端·c#
Raink老师16 分钟前
【AI面试临阵磨枪-98】前端如何展示多模态流式输出:文字打字机 + 图片渐进 + 音频播放?
前端·人工智能·面试
AI_零食19 分钟前
奶茶大数据运维表 - 鸿蒙PC Electron框架技术实现详解
运维·前端·华为·electron·开源·harmonyos·鸿蒙
小雨下雨的雨20 分钟前
鸿蒙PC Electron框架实现流体气泡模拟器
前端·人工智能·算法·华为·electron·鸿蒙
ZC跨境爬虫22 分钟前
跟着 MDN 学JavaScript day_4:如何存储你需要的信息——变量
开发语言·前端·javascript·ui·ecmascript
星栈独行24 分钟前
10 分钟跑起第一个 Makepad 应用:先把窗口开起来
前端·程序人生·ui·rust·开源·github