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

相关推荐
灵感__idea6 小时前
Hello 算法:贪心的世界
前端·javascript·算法
GreenTea7 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
killerbasd9 小时前
牧苏苏传 我不装了 4/7
前端·javascript·vue.js
吴声子夜歌9 小时前
ES6——二进制数组详解
前端·ecmascript·es6
码事漫谈9 小时前
手把手带你部署本地模型,让你Token自由(小白专属)
前端·后端
ZC跨境爬虫9 小时前
【爬虫实战对比】Requests vs Scrapy 笔趣阁小说爬虫,从单线程到高效并发的全方位升级
前端·爬虫·scrapy·html
爱上好庆祝9 小时前
svg图片
前端·css·学习·html·css3
橘子编程10 小时前
JavaScript与TypeScript终极指南
javascript·ubuntu·typescript
王夏奇10 小时前
python中的__all__ 具体用法
java·前端·python
叫我一声阿雷吧10 小时前
JS 入门通关手册(45):浏览器渲染原理与重绘重排(性能优化核心,面试必考
javascript·前端面试·前端性能优化·浏览器渲染·浏览器渲染原理,重排重绘·reflow·repaint