def setUp(self) -> None: self.base_page = BasePage(Browser().get_driver()) self.base_page.set_browser_max() self.base_page.implicitly_wait() self.base_page.open_url(local_config.url) self.test_data = TestDataUtils('main_suite', 'main_suite').get_test_data()
def request(self): try: with Database() as session: with Browser() as browser_session: url = self.url(Category.NEWSLETTER.value) response = browser_session.get(url) response.raise_for_status() soup = bs4.BeautifulSoup(response.content, 'html.parser') elements = soup.select('#content-left a') LOGGER.info('{} newsletters have been found'.format( len(elements))) if len(elements) == 0: LOGGER.info('Done, no more newsletters') return for element in reversed(elements): href = element['href'] title = element.text model, created = session.get_or_create(Newsletter, url=href, title=title) if not created: LOGGER.info( f'Newsletter "{href}" ...skipped (duplicate)') else: LOGGER.info(f'{href} ...added') except requests.exceptions.HTTPError as exc: LOGGER.warning('Scraping {} {} ...skipping'.format( url, exc.response.status_code)) raise exc
def request(self): with Database() as session: with Browser() as browser_session: url = self.url(Category.INVOICE.value) loop = True while loop: try: response = browser_session.get(url) response.raise_for_status() soup = bs4.BeautifulSoup(response.content, 'html.parser') elements = soup.select( '#dokumenty table.tabulka tr:not(.hlavicka)') if len(elements) == 0: LOGGER.info('Done, no more invoices') return for element in elements: published, _, title, _, _, _, document = element.findChildren( 'td') link = document.findChild('a').attrs.get('href') size_in_mb = re.search(r'([0-9\.]+)', document.text).groups()[0] is_pdf = re.search(r'\.pdf$', url) if is_pdf: model, created = session.get_or_create( Invoice, published=datetime.date.fromisoformat( published.text), title=title.text, url=link, size_in_mb=size_in_mb) if not created: LOGGER.info( f'Invoice {model.url} ...skipped (duplicate)' ) loop = False else: LOGGER.info(f'{model.url} ...added') else: LOGGER.warning( f'Invoice {model.url} ...skipped (not PDF)' ) next_url = soup.select_one( '#dokumenty table:first-of-type [align="right"] a:nth-last-child(2)' ).attrs.get('href') next_url = urljoin(self.base_url(response.url), next_url) # FIXME: first page can be w/o the page number if next_url == url: return url = next_url except requests.exceptions.HTTPError as exc: LOGGER.warning('Scraping {} {} ...skipping'.format( url, exc.response.status_code)) raise exc
def setUp(self): ''' 测试用例的初始化 :return: ''' logger.info('--------测试方法初始化---------------') self.base_page = BasePage(Browser().get_driver()) self.base_page.set_browser_max() self.base_page.implicitly_wait() self.base_page.open_url(local_config.url)
def request(self): try: with Database() as session: with Browser() as browser_session: url = self.url(Category.PROCUREMENT.value) response = browser_session.get(url) response.raise_for_status() soup = bs4.BeautifulSoup(response.content, 'html.parser') main_element = soup.select_one('#content-left ol') procurements = main_element.select('a') offers = main_element.find_next_siblings('a') LOGGER.info('{} procurements have been found'.format( len(procurements))) if len(procurements) == 0: LOGGER.info('Done, no more procurements') for element in procurements: href = element['href'] title = element.text model, created = session.get_or_create(Procurement, url=href, title=title) if not created: LOGGER.info( f'Procurement "{href}" ...skipped (duplicate)') else: LOGGER.info(f'{href} ...added') LOGGER.info('{} offers have been found'.format( len(offers))) if len(offers) == 0: LOGGER.info('Done, no more offers') return for element in offers: href = element['href'] title = element.text model, created = session.get_or_create(Procurement, url=href, title=title, is_offer=True) if not created: LOGGER.info( f'Offer "{href}" ...skipped (duplicate)') else: LOGGER.info(f'{href} ...added') except requests.exceptions.HTTPError as exc: LOGGER.warning('Scraping {} {} ...skipping'.format( url, exc.response.status_code)) raise exc
def setUpClass(cls): serino = "MDEVICE" #serino = "adede7a6" cls.url = "http://122.225.253.188/" if len(sys.argv) > 1: serino = sys.argv[1] if Configs("common").get("product", "Info") == "Sprints": cls.mod = Chrome(serino, "Browser") else: cls.mod = Browser(serino, "Browser") cls.set = Settings(cls.mod.device, "Settings")
def __init__(self,device,mod): self.device = connect_device(device) self.logger = createlogger(mod) self.log_path = create_folder() self.camera = Camera(self.device,"task_camera") self.product = Configs("common").get("product","Info") if self.product == "Sprints": from common.chrome import Chrome self.browser = Chrome(self.device,"task_browser") else: self.browser = Browser(self.device,"Browser") self.tel = Telephony(self.device,"task_tel") self.message = Message(self.device,"task_message") self.settings = Settings(self.device,"switch_nw") self.suc_times = 0 self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() for test_time in self.dicttesttimes: self.test_times += int(self.dicttesttimes[test_time]) self.test_times = self.test_times*2 + 4 self.logger.info("Trace Total Times " + str(self.test_times))
def __init__(self, device, mod): self.device = connect_device(device) self.logger = createlogger(mod) self.log_path = create_folder() self.camera = Camera(self.device, "task_camera") self.product = Configs("common").get("product", "Info") if self.product == "Sprints": from common.chrome import Chrome self.browser = Chrome(self.device, "task_browser") else: self.browser = Browser(self.device, "Browser") self.tel = Telephony(self.device, "task_tel") self.message = Message(self.device, "task_message") self.settings = Settings(self.device, "switch_nw") self.suc_times = 0 self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() for test_time in self.dicttesttimes: self.test_times += int(self.dicttesttimes[test_time]) self.test_times = self.test_times * 2 + 4 self.logger.info("Trace Total Times " + str(self.test_times))
def request(self): try: with Database() as session: with Browser() as browser_session: url = self.url(Category.BUDGET.value) response = browser_session.get(url) response.raise_for_status() soup = bs4.BeautifulSoup(response.content, 'html.parser') elements = soup.select('#content-left a') LOGGER.info('{} budgets have been found'.format( len(elements))) if len(elements) == 0: LOGGER.info('Done, no more budgets') return for element in reversed(elements): href = element['href'] title = element.text if not re.search(r'\d', title): sufix = element.findPreviousSibling('h2').text title = f'{title} {sufix}' model, created = session.get_or_create(Budget, url=href, title=title) if not created: LOGGER.info( f'Budget "{href}" ...skipped (duplicate)') else: LOGGER.info(f'{href} ...added') except requests.exceptions.HTTPError as exc: LOGGER.warning('Scraping {} {} ...skipping'.format( url, exc.response.status_code)) raise exc
def request(self): try: with Database() as session: with Browser() as browser_session: url = self.url(Category.REPORT.value) response = browser_session.get(url) response.raise_for_status() soup = bs4.BeautifulSoup(response.content, 'html.parser') elements = soup.select('#content-left tr') LOGGER.info('{} reports have been found'.format( len(elements))) if len(elements) == 0: LOGGER.info('Done, no more reports') return for element in elements: date, title = element.findChildren('td') title = re.sub(r'[\n\s]+', ' ', title.text) model, created = session.get_or_create( Report, date=date.text.strip(), title=title.strip()) if not created: LOGGER.info( f'Report "{model.title[:30]}..." ...skipped (duplicate)' ) else: LOGGER.info(f'"{model.title[:40]}..." ...added') except requests.exceptions.HTTPError as exc: LOGGER.warning('Scraping {} {} ...skipping'.format( url, exc.response.status_code)) raise exc
# @author: lvhuayan # @file: quit_action.py # @time: 2021/3/27 20:23 # @desc: from actions.login_action import LoginAction from common.browser import Browser from element_infos.login.login_page import LoginPage from element_infos.main.main_page import MainPage from common.config_utils import Config class QuitAction: def __init__(self, driver): self.main_page = MainPage(driver) def quit(self): self.main_page.click_username() self.main_page.click_quit() return LoginPage(self.main_page.driver) if __name__ == '__main__': driver = Browser().get_driver() driver.get('http://47.107.178.45/zentao/www/index.php?m=user&f=login') driver.maximize_window() driver.implicitly_wait(5) login_action = LoginAction(driver) main_page = login_action.default_login() main_page.implicitly_wait(5) QuitAction(main_page.driver).quit()
class MultiTask(Common): def __init__(self,device,mod): self.device = connect_device(device) self.logger = createlogger(mod) self.log_path = create_folder() self.camera = Camera(self.device,"task_camera") self.product = Configs("common").get("product","Info") if self.product == "Sprints": from common.chrome import Chrome self.browser = Chrome(self.device,"task_browser") else: self.browser = Browser(self.device,"Browser") self.tel = Telephony(self.device,"task_tel") self.message = Message(self.device,"task_message") self.settings = Settings(self.device,"switch_nw") self.suc_times = 0 self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() for test_time in self.dicttesttimes: self.test_times += int(self.dicttesttimes[test_time]) self.test_times = self.test_times*2 + 4 self.logger.info("Trace Total Times " + str(self.test_times)) def remove(self): self.logger.debug("remove all opened activities") self.device.press.menu() if self.device(description= "Clear all").wait.exists(timeout = 2000): self.device(description= "Clear all").click() self.device.delay(5) return True return False def start(self): self.logger.debug("Start Some activities") self.logger.debug("Launch Contacts") #self.tel.start_app("Contacts") self.tel.enter_contacts() self.device.delay(3) self.logger.debug("Launch Message") self.message.start_app("Messaging") self.device.delay(3) self.logger.debug("Launch Dialer") #self.tel.start_app("Call") self.tel.enter_dialer() self.device.delay(3) self.logger.debug("Launch Camera") self.camera.start_app("Camera") self.device.delay(3) self.logger.debug("Launch Browser") #self.browser.start_app("Browser") self.browser.enter() def make_call(self,number): if self.tel.enter_dialer(): try: if self.tel.call_from_dialer(number): self.suc_times += 1 self.logger.info("Trace Success Make Call") return True else: self.save_fail_img() return False except Exception,e: self.save_fail_img() # common.common.log_traceback(traceback.format_exc()) return False
import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from common.browser import Browser movie_name = "super deluxe" movie_name1 = "super-deluxe" browser = Browser.open_new_tab() browser.get("https://www.google.com") search_bar = browser.find_element_by_name('q') search_bar.send_keys('movierulz') search_bar.send_keys(Keys.ENTER) elems = browser.find_elements_by_xpath("//*[@href]") for elem in elems: if "movierulz." in elem.get_attribute("href"): browser.get(elem.get_attribute("href")) break time.sleep(1) search_bar = browser.find_element_by_name('s') search_bar.send_keys(movie_name) search_bar.send_keys(Keys.ENTER) elems = browser.find_elements_by_xpath("//*[@href]") for elem in elems: if movie_name1 in elem.get_attribute( "href") and "search" not in elem.get_attribute("href"): browser.get(elem.get_attribute("href")) break
def setUp(self) -> None: # 针对方法级别的 print('SeleniumBaseCase.setUp') self.base_page = BasePage(Browser().get_driver()) self.base_page.set_browser_max() self.base_page.implicitly_wait() self.base_page.open_url(self.url)
current_path = os.path.dirname(__file__) page_path = os.path.join(current_path, '../../pages/element_samples.html') class Sample06(BasePage): def __init__(self, driver): super().__init__(driver) elements = ElementDataUtils('sample06', 'sample06_page').get_element() self.select_menu = elements['select_menu'] self.government_service_link = elements['government_service_link'] def select_government(self, government_name): self.select_by_visible_text(self.select_menu, government_name) def click_government_service_link(self, nemu_name): self.government_service_link[ 'locator_value'] = self.government_service_link[ 'locator_value'] % nemu_name self.click(self.government_service_link) if __name__ == '__main__': sample06_page = Sample06(Browser().get_driver()) sample06_page.open_url('file://' + page_path) sample06_page.implicitly_wait() sample06_page.set_browser_max() sample06_page.select_government('开封教育网') sample06_page.switch_to_handle_by_title('开封市教育体育局') # sample06_page.switch_to_handle_by_url('http://jtj.kaifeng.gov.cn/') sample06_page.click_government_service_link('政务服务')
def __init__(self, page=None, browser_type='chrome'): if page: self.driver = page.driver else: # super(Page, self).__init__(browser_type=browser_type)新式写法,同下面经典写法 Browser.__init__(self, browser_type=browser_type)
# encoding:utf-8 # @author: lvhuayan # @file: login_page.py # @time: 2021/3/16 13:33 # @desc: import os from selenium import webdriver from common.base_page import BasePage from common.browser import Browser from common.element_data_utils import ElementDataUtils #测试base_page中switch_to_alert方法是否封装正确 current_path=os.path.dirname(__file__) page_path=os.path.join(current_path,'../../pages/element_samples.html') class Sample01(BasePage): def __init__(self,driver): super().__init__(driver) elements=ElementDataUtils('sample01','sample01_page').get_element() self.button_toalert=elements['button_toalert'] def click_alert_button(self):#点击测试alert弹框按钮 self.click(self.button_toalert) if __name__=='__main__': sample01_page=Sample01(Browser().get_driver()) sample01_page.open_url('file://'+page_path) sample01_page.implicitly_wait() sample01_page.click_alert_button() sample01_page.switch_to_alert()
class MultiTask(Common): def __init__(self, device, mod): self.device = connect_device(device) self.logger = createlogger(mod) self.log_path = create_folder() self.camera = Camera(self.device, "task_camera") self.product = Configs("common").get("product", "Info") if self.product == "Sprints": from common.chrome import Chrome self.browser = Chrome(self.device, "task_browser") else: self.browser = Browser(self.device, "Browser") self.tel = Telephony(self.device, "task_tel") self.message = Message(self.device, "task_message") self.settings = Settings(self.device, "switch_nw") self.suc_times = 0 self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() for test_time in self.dicttesttimes: self.test_times += int(self.dicttesttimes[test_time]) self.test_times = self.test_times * 2 + 4 self.logger.info("Trace Total Times " + str(self.test_times)) def remove(self): self.logger.debug("remove all opened activities") self.device.press.menu() if self.device(description="Clear all").wait.exists(timeout=2000): self.device(description="Clear all").click() self.device.delay(5) return True return False def start(self): self.logger.debug("Start Some activities") self.logger.debug("Launch Contacts") #self.tel.start_app("Contacts") self.tel.enter_contacts() self.device.delay(3) self.logger.debug("Launch Message") self.message.start_app("Messaging") self.device.delay(3) self.logger.debug("Launch Dialer") #self.tel.start_app("Call") self.tel.enter_dialer() self.device.delay(3) self.logger.debug("Launch Camera") self.camera.start_app("Camera") self.device.delay(3) self.logger.debug("Launch Browser") #self.browser.start_app("Browser") self.browser.enter() def make_call(self, number): if self.tel.enter_dialer(): try: if self.tel.call_from_dialer(number): self.suc_times += 1 self.logger.info("Trace Success Make Call") return True else: self.save_fail_img() return False except Exception, e: self.save_fail_img() # common.common.log_traceback(traceback.format_exc()) return False
def setUp(self) -> None: self.base_page = BasePage(Browser().get_driver()) self.base_page.set_browser_max() self.base_page.implicitly_wait() self.base_page.open_url(local_config.url)
#测试base_page中select下拉框方法是否封装正确 current_path = os.path.dirname(__file__) page_path = os.path.join(current_path, '../../pages/element_samples.html') class Sample03(BasePage): def __init__(self, driver): super().__init__(driver) elements = ElementDataUtils('sample03', 'sample03_page').get_element() self.select_menu = elements['select_menu'] def select_menu_value1(self, content): self.select_by_visible_text(self.select_menu, content) def select_menu_value2(self, content): self.select_by_value(self.select_menu, content) def select_menu_value3(self, content): self.select_by_index(self.select_menu, content) if __name__ == '__main__': sample03_page = Sample03(Browser().get_driver()) sample03_page.set_browser_max() sample03_page.open_url('file://' + page_path) sample03_page.implicitly_wait() # sample03_page.select_menu_value1('香蕉') # sample03_page.select_menu_value2('peach') sample03_page.select_menu_value3(4)
def setUpClass(cls): print('==========测试类开始初始化================') cls.base_page = BasePage(Browser().get_driver()) cls.base_page.set_browser_max() cls.base_page.implicitly_wait() cls.base_page.open_url(local_config.url)
def setUp(self) -> None: logger.info('♥❤♥❤测试方法开始执行♥❤♥❤!') self.base_page = BasePage(Browser().get_driver()) self.base_page.set_driver()
import os,time from selenium import webdriver from selenium.webdriver.common.by import By from actions.login_action import loginAction from common.log_utlis import logger from common.base_page import BasePage from common.element_data_utils import ElementdataUtils from common.browser import Browser driver = Browser().get_driver() driver.get('http://127.0.0.1:81/index.php') main_page = loginAction(driver).default_login() value=main_page.get_username() print(value)
def setUp(self): self.base_page = BasePage(Browser().get_driver()) self.base_page.set_maxwindow() self.base_page.implicitly_wait() self.base_page.open_url(self.url)
self.wait(1) def goto_project(self): # 进入项目菜单 self.click(self.project_menu) self.wait(1) def goto_organization(self): self.click(self.organization_menu) self.wait(1) def get_username(self): # return self.get_text(self.username_showspan) if __name__ == "__main__": driver = Browser().get_driver() # 登录 login_page = LoginPage(driver) login_page.open_url('http://127.0.0.1/zentao/user-login.html') login_page.set_browser_max() login_page.input_username('admin') login_page.input_password('admin123456') login_page.click_login() login_page.wait(2) # 主页操作 main_page = MainPage(login_page.driver) text = main_page.get_username() print(text) # main_page.goto_myzone() # main_page.goto_product()
super().__init__(driver) elements = ElementDataUtils('sample02', 'sample02_page').get_element() self.frame_xpath = elements['frame_xpath'] self.input01_inputbox = elements['input01_inputbox'] self.input02_inputbox = elements['input02_inputbox'] self.span_text = elements['span_text'] def frame_info(self): self.switch_to_frame(self.frame_xpath) def input_text01(self, content): self.input(self.input01_inputbox, content) def input_text02(self, content): self.input(self.input02_inputbox, content) def get_span_text(self): self.get_text(self.span_text) if __name__ == '__main__': sample02_page = Sample02(Browser().get_driver()) sample02_page.open_url('file://' + page_path) sample02_page.implicitly_wait() sample02_page.frame_info() # sample02_page.switch_to_frame_id_or_name('frame1') sample02_page.input_text01('newdream') sample02_page.input_text02('test') sample02_page.switch_to_default_content() sample02_page.get_span_text()
def login_action(self, username, password): self.login_page.input_username(username) self.login_page.input_password(password) self.login_page.click_login() def login_success(self, username, password): self.login_action(username, password) return MainPage(self.login_page.driver) def default_login(self): self.login_success(username=config.user_name, password=config.pass_word) def login_fail(self, username, password): self.login_action(username, password) value = self.login_page.get_login_fail_alert(type='yes', selector='alert') return value def login_by_cookie(self): pass if __name__ == '__main__': driver1 = Browser().get_driver() loginaction = LoginAction(driver1) driver1.get( 'http://106.53.50.202:8999/zentao2/www/user-login-L3plbnRhbzYvd3d3Lw==.html' ) loginaction.login_success('chenjuan', '1q2w3e4r,')
def delete_attribute01(self, content): self.delete_element_attribute01(self.show_select_result, content) def execute_js1(self, js_str): self.execute_script(js_str, self.show_select_result) def execute_js2(self, js_str): self.execute_script(js_str) def update_attribute(self, attribute_name, attribute_value): self.update_element_attribute(self.show_select_result, attribute_name, attribute_value) if __name__ == '__main__': sample04_page = Sample04(Browser().get_driver()) sample04_page.set_browser_max() sample04_page.open_url('file://' + page_path) sample04_page.implicitly_wait() # sample04_page.delete_attribute('value') sample04_page.delete_attribute01('value') # sample04_page.update_attribute('value','newdream') # js_str1= 'arguments[0].removeAttribute("value");' # sample04_page.execute_js1(js_str1) # js_str2='document.body.scrollTop=%d;' # sample04_page.execute_js2(js_str2%5000)
from elements_infos.login.login_page import LoginPage from elements_infos.main.main_page import MainPage from common.config_utils import local_config from common.browser import Browser class QuitAction: def __init__(self, driver): self.main_page = MainPage(driver) def quit(self): self.main_page.click_username() self.main_page.click_quit_button() return LoginPage(self.main_page.driver) if __name__ == '__main__': driver = Browser().get_driver() driver.get('http://47.107.178.45/zentao/www/index.php?m=user&f=login')
#调用父类方法 def clickzaotao(self): self.click(self.caotao_button) def inputusername(self,username): self.input(self.username_inputbox,username) def inputuserpassword(self,password): self.input(self.userpassword_inputbox,password) def clicklogin(self): self.click(self.login_button) def switch_accept(self): self.accept() if __name__=="__main__": try: dri=Browser('chrome').getdriver() driver=LoginPage(dri) driver.openurl('http://106.53.50.202:8999/zentao3/www/user-login-L3plbnRhbzYvd3d3Lw==.html') driver.waittime() driver.setmaxbrowser() driver.inputusername('admin') driver.inputuserpassword('a12345678') driver.clicklogin() driver.waittime(2) finally: driver.quitbrowsr()
def setUp(self) -> None: logger.info('-------------测试方法开始执行------------') self.base_page = BasePage(Browser().get_driver()) self.base_page.set_browser_max() self.base_page.implicitly_wait() self.base_page.open_url(self.url)
def setUp(self) -> None: self.base_page = Basepage(Browser().get_chrome_dirver()) self.base_page.set_browser_max() self.base_page.implicitly_wait() self.base_page.open_url(config.get_url_path)