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

相关推荐
不绝19116 小时前
C#核心——面向对象:封装
开发语言·javascript·c#
276695829216 小时前
dy bd-ticket-guard-client-data bd-ticket-guard-ree-public-key 逆向
前端·javascript·python·abogus·bd-ticket·mstoken·ticket-guard
m0_7263658316 小时前
哈希分分预测系统 + Python Worker + Web 仪表盘”小系统(PHP + MySQL)
前端·python·哈希算法
WX-bisheyuange16 小时前
基于SpringBoot的交通管理在线服务系统
前端·javascript·vue.js·毕业设计
WHOVENLY17 小时前
揭秘正则表达式的基础语法与应用
开发语言·javascript·正则表达式
程序员雷叔17 小时前
在postman设置请求里带动态token,看看这两种方法!
selenium·测试工具·单元测试·测试用例·pytest·lua·postman
Coder_Boy_17 小时前
基于SpringAI的在线考试系统-考试系统DDD(领域驱动设计)实现步骤详解(2)
java·前端·数据库·人工智能·spring boot
GIS之路17 小时前
ArcGIS Pro 实现影像波段合成
前端·python·信息可视化
m0_7482546617 小时前
CSS id 和 classid 和 class 选择器
前端·css
光算科技17 小时前
单页应用SEO可行性丨Angular项目的3个索引优化方案
前端·javascript·angular.js