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