예제 #1
0
    def click_img(self, answer, height, identify_img_xpath1=None,
                  identify_button_xpath=None):
        """
        根据打码返回的坐标进行点击操作
        仅适用与点击型验证码

        :param answer: 打码返回结果
        :param height: 答案高度
        :param identify_img_xpath1: 题目xpath
        :param identify_button_xpath: 验证按钮
        :return:
        """
        actions = ActionChains(self.driver)
        img = self.driver.find_element_by_xpath(identify_img_xpath1)
        points = answer.split('|')
        for point in points:
            x, y = eval(point)
            actions.move_to_element_with_offset(
                img, x, y - int((height / self.device_pixel_ratio)))
            actions.click()
        actions.perform()
        time.sleep(2)
        if not identify_button_xpath:
            return
        self.driver.find_element_by_xpath(identify_button_xpath).click()
예제 #2
0
    def test_search_in_python_org(self):
        driver = self.driver
        driver.implicitly_wait(5)
        actions = ActionChains(driver)
        driver.get("http://localhost:8080")

        value = driver.find_element_by_css_selector('.graph')
        actions.click(on_element=value)
        actions.perform()

        menu = driver.find_element_by_id('VIZ_popup_menu')
        buttons = driver.find_elements_by_css_selector('#VIZ_popup_menu button')
        for button in buttons:
            text = button.get_attribute('textContent')
            if text == 'Set range':
                button.click()
                WebDriverWait(driver, 5).until(EC.alert_is_present())
                alert = driver.switch_to_alert()
                alert.send_keys("-0.1,0.1")
                alert.accept()
                break
                
        tick = driver.find_element_by_css_selector('g.axis:nth-child(4) > g:nth-child(1)')
        text = tick.get_attribute('textContent')
        assert text == "-0.1"
예제 #3
0
    def click_menu_option_by_visible_text(self, menu_locator, list_of_menu_options):
        """
        Performs support move_to_element action on every link <support...> contained in
        menu_locator if its visible text matches any of the names defined in
        list_of_menu_options and clicks on the last matching link.

        :param menu_locator:
        :param list_of_menu_options: 
        """
        menu_options = self.driver.find_elements(*menu_locator)
        actions = ActionChains(self.driver)
        menu_index = 0
        expected_option = None
        for option in menu_options:
            if menu_index >= len(list_of_menu_options):
                break
            if expected_option is None:
                expected_option = list_of_menu_options[menu_index].strip()

            if option.get_attribute('title') == expected_option or option.get_attribute(
                    'text') == expected_option or option.text == expected_option:
                actions.move_to_element(option)
                menu_index += 1
                expected_option = None
        actions.click()
        actions.perform()
    def test_tamplate(self):
        ''' Test a situation when unlogged user tries to download a file '''
        item_to_download = WebDriverWait(self.driver, 10).until(
            ec.visibility_of_element_located((By.CLASS_NAME, 'ent-title')))
        
        action = ActionChains(self.driver)
        action.move_to_element(item_to_download)
        action.click(item_to_download)
        action.perform()

        time.sleep(5)

        download_button = self.driver.find_elements_by_class_name('download')
        download_button_1 = download_button[0]
        download_button_2 = download_button[1]

        action = ActionChains(self.driver)
        action.move_to_element(download_button_2)
        action.click(download_button_2)
        action.perform()
        time.sleep(8)

        #Alert message
        try:
            alert_message = WebDriverWait(self.driver, 10).until(
            ec.visibility_of_element_located((By.CLASS_NAME, 'xw-hdr-text')))
        finally:
            print ('oops')
예제 #5
0
파일: _tester.py 프로젝트: 151706061/X
  def visit( self, url ):
    '''
    '''

    if self.__jscoverage_loaded:

      self.__browser.switch_to_window( self.__browser.window_handles[0] )

    else:

      # load JSCoverage
      self.__browser.get( "http://localhost:8080/jscoverage.html" )
      self.__jscoverage_loaded = True


    # clear the jscoverage location field
    locationfield = self.__browser.find_element_by_id( 'location' )
    locationfield.clear()

    # fill in url
    actions = ActionChains( self.__browser )
    actions.click( locationfield )
    actions.send_keys( url )
    actions.send_keys( Keys.TAB )
    actions.send_keys( Keys.TAB )
    actions.send_keys( Keys.RETURN )
    actions.perform()

    # switch to the new window
    self.__browser.switch_to_window( self.__browser.window_handles[-1] )
def test_basic_functionality(driver, test_file):
	try:
		#Test page response by clicking the reset button and applying new code to ace-editor

		tt.reset_page(driver)
		tt.update_editor(driver, test_file)
		ens_elements = driver.find_elements_by_xpath('//*[@class="ens"]')
		assert (len(ens_elements) > 0)
		side_script = '''var right = document.getElementById("rightpane"); \
		right.style.width = "200px"
		'''
		driver.execute_script(side_script)

		#Creates graph objects by right clicking on nodes and selecting from menu
		actions = ActionChains(driver)
		elements = ['node', 'ens']
		for elem in elements:
			node = driver.find_element_by_xpath('//*[@class="'+elem+'"]')
			actions = ActionChains(driver)
			actions.move_to_element(node)
			actions.context_click()
			actions.perform()
			time.sleep(1)
			actions = ActionChains(driver)

			menu = driver.find_element_by_xpath('//*[@class="dropdown-menu"]/li[1]')
			actions.move_to_element(menu)
			actions.click()
			actions.perform()
			time.sleep(0.5)

		graph_elements = driver.find_elements_by_xpath('//*[@class="graph"]')

		assert len(graph_elements) > 0
		tt.start_stop_sim(driver)
		time.sleep(1.5)
		tt.start_stop_sim(driver)
		time.sleep(0.5)

		ticker = driver.find_element_by_xpath('//*[@id="ticks_tr"]/td')
		sim_time = ticker.get_attribute('textContent')

		assert (float(sim_time) > 0)

	except Exception as e:
		#Travis Only: On fail takes screenshot and uploads it to imgur


		if('TRAVIS' in os.environ):
			tt.imgur_screenshot(driver)

		_, _, tb = sys.exc_info()
		traceback.print_tb(tb) # Fixed format
		tb_info = traceback.extract_tb(tb)
		filename, line, func, text = tb_info[-1]

		print('An error occurred on line {} in statement {}'.format(line, text))
		print(str(e))
		exit(1)
예제 #7
0
파일: Auto.py 프로젝트: JJ97/Hash
def stop():
	main_window = driver.current_window_handle
	driver.switch_to_window(main_window)
	actions = ActionChains(driver)
	stop = driver.find_element_by_xpath("//span[contains(text(), 'stop')]")
	actions.move_to_element(stop)
	actions.click(stop)
	actions.perform()
 def do_it(self):
     
     mouse_move_to_menu_themes = ActionChains(self.driver)
     mouse_move_to_menu_themes.move_to_element(self.menu)
     mouse_move_to_menu_themes.move_to_element(self.tab)
     mouse_move_to_menu_themes.move_to_element(self.subitem)
     mouse_move_to_menu_themes.click(self.subitem)
     mouse_move_to_menu_themes.perform()
     time.sleep(5)
예제 #9
0
 def get_properties(self, name, prefix=None):
     self.show_properties()
     self.show_dataflow()
     obj = self.get_dataflow_figure(name, prefix=prefix)
     chain = ActionChains(self.browser)
     chain.click(obj.root)
     chain.perform()
     time.sleep(0.5)
     return (self.props_header, self.props_inputs, self.props_outputs)
예제 #10
0
    def test_search_in_python_org(self):
        driver = self.driver
        actions = ActionChains(driver)

        driver.get("http://localhost:8000")

        # Test for text in editor
        elem = driver.find_element_by_id('menu_nengo_viz')
        actions.click(elem)
def mouse_move_to_menu():
           
        mouse_move_to_menu_themes = ActionChains(driver)
        mouse_move_to_menu_themes.move_to_element(menu)
        mouse_move_to_menu_themes.move_to_element(tab)
        mouse_move_to_menu_themes.move_to_element(subitem)
        mouse_move_to_menu_themes.click(subitem)
        mouse_move_to_menu_themes.perform()
        time.sleep(5)
예제 #12
0
def clicketi_click_list_row(context, item):
    """
    This is a special clicketi click for list items that might not be clickable
    in the middle.
    """
    action_chain = ActionChains(context.browser)
    action_chain.move_to_element_with_offset(item, item.size['width'] / 4, item.size['height'] / 2)
    action_chain.click()
    action_chain.perform()
예제 #13
0
def clickElement(element):
    if useNativeEvents > 0:
        # move and click the mouse like a user
        actions = ActionChains(driver)
        actions.click(element)
        actions.perform()
    else:
        # use the traditional accessibility action
        element.click()
예제 #14
0
 def create_rerun(self, course_key):
     """
     Clicks the create rerun link of the course specified by course_key
     'Re-run course' link doesn't show up until you mouse over that course in the course listing
     """
     actions = ActionChains(self.browser)
     button_name = self.browser.find_element_by_css_selector('.rerun-button[href$="' + course_key + '"]')
     actions.move_to_element(button_name)
     actions.click(button_name)
     actions.perform()
예제 #15
0
    def test_report(self):
        self.browser.get(self.live_server_url + '/')

        # Login
        username = self.browser.find_element_by_id('username')
        username.send_keys('Jim')
        password = self.browser.find_element_by_id('password')
        # Send the wrong password
        password.send_keys('correcthorsebatterystaple')

        # Submit the form
        submit = self.browser.find_element_by_id('submit')
        submit.click()

        # Navigate to the sale page
        img = self.browser.find_element_by_xpath(
            '//div[@class="card small grey darken-3"][1]//img[@id="report-image"]')
        img.click()

        # Get the choose showing modal
        showing = self.browser.find_element_by_xpath(
            '//div[@class="col s6 center-align"][1]/button')
        showing.click()

        wait = WebDriverWait(self.browser, 10)
        element = wait.until(EC.element_to_be_clickable((By.ID, 'picker-modal')))

        modal = self.browser.find_element_by_id('picker-modal')
        self.assertTrue(modal.is_displayed())

        occ = self.browser.find_element_by_id('showing')
        occ.click()

        free_text = self.browser.find_element_by_xpath('//div[@id="sale-update"]//p').text
        self.assertIn('No tickets sold', free_text)
        self.assertIn('No tickets reserved', free_text)
        self.assertIn('80 tickets left', free_text)

        # Check selling tickets adds up properly
        pricing = models.InHousePricing.objects.get(id=1)
        member_price = pricing.member_price
        concession_price = pricing.concession_price
        public_price = pricing.public_price
        mat_f_price = pricing.matinee_freshers_price
        mat_f_nnt_price = pricing.matinee_freshers_nnt_price

        out = self.browser.find_element_by_id('out1').text

        member = self.browser.find_element_by_id('member')
        action = ActionChains(self.browser)
        action.click(on_element=member)
        action.send_keys('1')
        action.key_down(Keys.CONTROL)
        action.key_up(Keys.CONTROL)
        action.perform()
예제 #16
0
    def test_search_in_python_org(self):
        driver = self.driver
        driver.implicitly_wait(10)
        actions = ActionChains(driver)

        driver.get("http://localhost:8000")
        elem = driver.find_element_by_id('menu_open')
        actions.click(elem)
        actions.perform()

        nothing = driver.find_element_by_css_selector('.nothinghere')
예제 #17
0
파일: Auto.py 프로젝트: JJ97/Hash
def run():
	# Ensure current window is the one in focus
	main_window = driver.current_window_handle
	driver.switch_to_window(main_window)
	actions = ActionChains(driver)
	# Find run button
	run = driver.find_element_by_xpath("//span[contains(text(), 'run')]")
	actions.move_to_element(run)
	# Click it
	actions.click(run)
	actions.perform()
 def click_to_tab_link(self, tab_link):
     mouse_move_to_menu = ActionChains(self.driver)
     mouse_move_to_menu.move_to_element(tab_link)
     mouse_move_to_menu.click(tab_link)
     mouse_move_to_menu.perform()
     time.sleep(5)
     WebDriverWait (self.driver, 10).until(ec.title_is(self.driver.title))
     current_page_info = {}
     current_page_info['current_page_title'] = self.driver.title.encode('utf-8')
     current_page_info['current_url'] = self.driver.current_url
     return (current_page_info)
예제 #19
0
파일: mayday.py 프로젝트: mistio/mist.tests
def rule_value(context, value):
    value_input = context.browser.find_element_by_xpath("//paper-input[@id='metricValue']")
    actions = ActionChains(context.browser)
    actions.move_to_element(value_input)
    actions.click()
    actions.send_keys(Keys.BACK_SPACE)
    actions.perform()

    actions.move_to_element(value_input)
    actions.click()
    actions.send_keys("0")
    actions.perform()
예제 #20
0
def clicketi_click(context, button):
    """
    trying two different ways of clicking a button because sometimes the
    Chrome driver for no apparent reason misinterprets the offset and
    size of the button
    """
    try:
        button.click()
    except WebDriverException:
        action_chain = ActionChains(context.browser)
        action_chain.move_to_element(button)
        action_chain.click()
        action_chain.perform()
예제 #21
0
    def answer_problem(self, correctness):
        """
        Answer image problem.
        """
        offset = 25 if correctness == 'correct' else -25
        input_selector = ".imageinput [id^='imageinput_'] img"
        input_element = self.problem_page.q(css=input_selector)[0]

        chain = ActionChains(self.browser)
        chain.move_to_element(input_element)
        chain.move_by_offset(offset, offset)
        chain.click()
        chain.perform()
예제 #22
0
def get_html(url, page):
    driver = webdriver.Chrome('D:/Program Files (x86)/chromedriver_win32/chromedriver.exe')
    driver.set_window_size(1920, 1080)

    # 关键词:性感男人 by URL编码
    driver.get(url)

    time.sleep(5)
    # 通过Xpath找到More button
    load_more = driver.find_element_by_xpath('//*[@id="pageMore"]')#baidupic
    print('gggggggg')
    a = 0
    stop = False;
    while(True):
        scroll_num = 0
        while (load_more.get_attribute('style')!="visibility: visible;"):
            driver.execute_script("scrollTo(0,document.body.scrollHeight);")
            sleep_time = 5
            time.sleep(sleep_time)
            scroll_num += 1
            if scroll_num > 10:
                stop = True
                break
        # print('start')
        # 模拟用户行为点击加载更多按键
        if stop:
            break
        actions = ActionChains(driver)
        actions.move_to_element(load_more)
        actions.click(load_more)
        actions.perform()

        driver.execute_script("scrollTo(0,document.body.scrollHeight);")
        sleep_time = 5
        print(sleep_time)
        time.sleep(sleep_time)
        print(load_more.get_attribute('style'))
        a += 1
        print(a)

    html = driver.execute_script("return document.getElementsByTagName('body')[0].innerHTML")
    driver.close()
    html = html.encode('UTF-8')
    print(html)
    # 将爬到的html写入文件
    mkdir(os.path.dirname(OUTPUT_HTML))
    with open(OUTPUT_HTML, 'w') as fw:
        fw.write(html)
        fw.close
    print("end")
    return html
예제 #23
0
def test_data_to_csv(driver):
	tt.reset_page(driver)

	tt.update_editor(driver,'''
import nengo
model = nengo.Network()
with model:
    stim = nengo.Node([0])
    a = nengo.Ensemble(n_neurons=50, dimensions=1)
    nengo.Connection(stim, a)
		''')

	time.sleep(1)

	actions = ActionChains(driver)
	elements = ['node','ens']
	for elem in elements:
		for x in range(2):
			node = driver.find_element_by_xpath('//*[@class="'+elem+'"]')

			actions = ActionChains(driver)
			actions.move_to_element(node)
			actions.context_click()
			actions.perform()
			time.sleep(1)
			actions = ActionChains(driver)

			menu = driver.find_element_by_xpath('//*[@class="dropdown-menu"]/li['+str(x+1)+']')
			actions.move_to_element(menu)
			actions.click()
			actions.perform()

			time.sleep(0.5)
	driver.execute_script("""a = function(){var data_set = Nengo.Component.components
data_set.forEach(function(data,index){
if(data.constructor === Nengo.Value){
   data.data_store.reset();
   data.data_store.push([1,10+index]);
};
}); return data_to_csv(data_set)};""")

	time.sleep(1)

	result = driver.execute_script("return a()")
	print result
	test_data = '''Graph Name,stim,a
Times,Dimension1,Dimension1
1,11,12'''

	assert result == test_data
예제 #24
0
 def addUser(name,passwd,confirmpasswd,email,telephone):
     action_chains = ActionChains(driver)
     action_chains.move_to_element(driver.find_element_by_link_text("用户管理")).perform()
     action_chains.click(driver.find_element_by_link_text("注册用户")).perform()
     driver.find_element_by_id("username").send_keys(name)
     driver.find_element_by_id("password").send_keys(passwd)
     driver.find_element_by_id("confirmpassword").send_keys(confirmpasswd)
     driver.find_element_by_id("email").send_keys(email)
     driver.find_element_by_id("telephone").send_keys(telephone)
     driver.find_element_by_name("strPrivilegeName()").click()
     driver.find_element_by_id("RegisterBut").click()
     alert = self.driver.switch_to_alert()
     alert.accept()
     time.sleep(3)
    def click_list_of_brands(self, click_here):
        _brand = self.driver.find_element(*MenuObject.BRAND_LNK)
        hover = ActionChains(self.driver).move_to_element(_brand)
        hover.perform()

        _brand_list = self.driver.find_element(*MenuObject.BRAND_MENU_LIST)
        _brand_items = _brand_list.find_elements_by_xpath('//*[@id="mtnav"]/li[1]/div/div/div/ul/li[2]/a/span')


        for item in _brand_items:

            if str(item.text) == str(click_here):
                item_click = ActionChains(self.driver).move_to_element(item)
                item_click.click().perform()
예제 #26
0
 def voit(self):
     try:
         with timeout(120):  # AVOID AUTH WINDOW
             self.driver.get(self.ROOT_URL)
             WebDriverWait(self.driver, 20)
             actions = ActionChains(self.driver)
             # li = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div[1]/div[1]/ul/li[38]/div/div[1]/ul/li[6]/a')
             lli = self.driver.find_element_by_css_selector('#content > div > div.large-12.columns > div:nth-child(2) > div.large-8.columns > ul > li:nth-child(38) > div > div.large-7.columns > ul > li:nth-child(6) > a')
             actions.click(lli)
             print "clicked"
     except (Exception,) as e:
         print e
     finally:
         self.driver.quit()
예제 #27
0
 def test_switch_to_test_plan_perspective(self):
     """Switch to test plan perspective after login"""
     driver = self.driver
     wait = WebDriverWait(driver, 10)
     test_perspective_button = wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/masthead/div/div[3]/div/div[2]/span[1]")))
     actions = ActionChains(driver)
     actions.move_to_element(test_perspective_button)
     actions.perform()
     time.sleep(2)
     actions2 = ActionChains(driver)
     test_plan = wait.until(EC.presence_of_element_located((By.XPATH, "/html/body/masthead/div/div[3]/div/div[2]/ul/li[1]")))
     actions2.move_to_element(test_plan)
     actions2.click(test_plan)
     actions2.perform()
     time.sleep(5)
예제 #28
0
def userAdd():
    count=1
    #依次注册用户列表中的用户
    for name in names:    
        #选择用户管理
        print "选择用户管理"
        action_chains = ActionChains(dbackupServer)
        action_chains.move_to_element(dbackupServer.find_element_by_link_text("用户管理")).perform()
        action_chains.click(dbackupServer.find_element_by_link_text("注册")).perform()
        #dbackupServer.find_element_by_xpath("/html/body/div[2]/table/tbody/tr[1]/td/table/tbody/tr[2]/td/div/ul[1]/li[3]/a").click()        
        #选择用户注册
        print "#选择用户注册"
        #dbackupServer.find_element_by_xpath("/html/body/div[2]/table/tbody/tr[1]/td/table/tbody/tr[2]/td/div/ul[1]/li[3]/ul/li[2]/a").click()
        #设置等待时间
        dbackupServer.implicitly_wait(5)
        #输入用户名
        dbackupServer.find_element_by_id("username").clear()
        dbackupServer.find_element_by_id("username").send_keys(name)
        #输入用户密码,密码为用户名+123456
        userPassword='******'
        dbackupServer.find_element_by_id("strPassword").clear()
        dbackupServer.find_element_by_id("strPassword").send_keys(userPassword)
        #重复输入密码
        dbackupServer.find_element_by_id("confirmpassword").clear()
        dbackupServer.find_element_by_id("confirmpassword").send_keys(userPassword)
        #输入邮箱,邮箱为用户名@scutech.com
        emailAddress=name+'@scutech.com'
        dbackupServer.find_element_by_id("email").clear()
        dbackupServer.find_element_by_id("email").send_keys(emailAddress)
        #输入联系方式,为了简便直接输入用户名
        dbackupServer.find_element_by_id("telephone").clear()
        dbackupServer.find_element_by_id("telephone").send_keys(name)
        #为前面6个加上系统管理权限
        if count<=6:
            dbackupServer.find_element_by_xpath("/html/body/div[2]/table/tbody/tr[2]/td/table/tbody/tr[3]/td/table/tbody/tr[12]/td[2]/table/tbody/tr/td[1]/label/input").click()
            count=count+1
        #点击“提交”按钮
        dbackupServer.find_element_by_id("RegisterBut").click()
 	    #设置等待时间
	    #time.sleep(3)       
        a=dbackupServer.switch_to_alert()
        a.accept()
        driver.Navigate().Back()
        time.sleep(3)
        action_chains.move_to_element(dbackupServer.find_element_by_link_text("授权管理")).perform()	
        action_chains.click(dbackupServer.find_element_by_link_text("序列号信息")).perform()    

    print 'regist done!'
    def _go_to_next_contact(self):
        """
        Goes to next contact chat in contact list. This is done by locating the "search" box and
        pressing tab and then arrow down.
        """
        actions = ActionChains(self.browser)
        try:
            actions.click(self.wait_for_element('.input.input-search')).send_keys(Keys.TAB).send_keys(
                Keys.ARROW_DOWN).perform()
        except StaleElementReferenceException:
            # Element is removed from the DOM structure, that happens when whatsapp refresh
            # the page and we don't want to break the app. I'm retying again after 2 sec.
            time.sleep(3)

            actions.click(self.wait_for_element('.input.input-search')).send_keys(Keys.TAB).send_keys(
                Keys.ARROW_DOWN).perform()
예제 #30
0
    def click_navigation_item(self, item_text, subitem_index=None):
        nav = self.selenium.find_element(*self._navigation_locator)
        ac = ActionChains(self.selenium)
        for item in nav.find_elements(By.CSS_SELECTOR, 'li'):
            if item.text == item_text:
                if subitem_index is None:
                    ac.click(item)
                else:
                    ac.move_to_element(item)
                    subitems = item.find_elements(By.CSS_SELECTOR, 'ul > li > a')
                    ac.click(subitems[subitem_index])
                break
        else:
            raise Exception('Navigation item %s not found.' % item_text)

        ac.perform()
예제 #31
0
    try:
        WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,\
        "//div[@class='btn norm bronze grey back']")))
        vc = browser.find_element_by_xpath(
            "//div[@class='btn norm bronze grey back']").click()
        vcc += 1
        break
    except TimeoutException:
        pass

    WebDriverWait(browser, 45).until(EC.visibility_of_element_located((By.XPATH, \
    "//canvas[@width='1024']")))

    tp = ActionChains(browser)
    tp.move_by_offset(1045, 318)
    tp.click()
    tp.perform()
    #Congratulations

    try:
        WebDriverWait(browser, 35).until(EC.element_to_be_clickable((By.XPATH, \
         "//div[@class='btn-box']//div[3]")))
        vc = browser.find_element_by_xpath(
            "//div[@class='btn-box']//div[3]").click()
    except TimeoutException:
        pass

    #"//div[@class='btn-box']//div[3]"

    #Close
    WebDriverWait(browser, 55).until(EC.element_to_be_clickable((By.XPATH,\
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
import time

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.implicitly_wait(10)

driver.get("https://app.hubspot.com/login")
driver.implicitly_wait(5)

username_ele = driver.find_element(By.ID, "username")
password_ele = driver.find_element(By.ID, "password")
login_button_ele = driver.find_element(By.ID, "loginBtn")

act_chains = ActionChains(driver)
act_chains.send_keys_to_element(username_ele, '*****@*****.**')
act_chains.send_keys_to_element(password_ele, 'Krupa2011')
act_chains.click(login_button_ele).perform()

time.sleep(5)

driver.quit()
예제 #33
0
    def runTest(self):
        driver = self.getDriver()
        param = self.param
        tool = utils
        driver.refresh()
        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()
        sleep(1)
        # 进入社交协同
        driver.find_element_by_xpath('//*[text()="财务管理"]').click()
        sleep(1)
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="财务报表"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(1)
        # 进入二级节点
        menu3 = driver.find_element_by_css_selector(
            'li[class="bottomBar"][title="报表数据审核"]')
        actions.move_to_element(menu3)
        actions.click(menu3)
        actions.perform()

        sleep(1)
        titleName = driver.find_element_by_css_selector(
            '#home_header > div > div.tab--38iB- > ul > li > p').get_attribute(
                'title')

        assert u"报表数据审核" in titleName, u"页面源码中不存在该关键字!"
        sleep(1)
        iframe = driver.find_element_by_id("reportDataAudit")
        driver.switch_to.frame(iframe)

        # 点击右边的按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//label[text()="报表模型"]/following-sibling::div//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
                )))
        driver.find_element_by_xpath(
            '//label[text()="报表模型"]/following-sibling::div//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
        ).click()

        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//div[@role="listbox"]/div[1]')))
        # 选自第一个条目
        driver.find_element_by_xpath('//div[@role="listbox"]/div[1]').click()

        # 点击年度右侧的按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//label[text()="年度"]/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
                )))
        driver.find_element_by_xpath(
            '//label[text()="年度"]/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
        ).click()

        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//div[@role="listbox"]/div[2]')))
        # 选自第一个条目
        driver.find_element_by_xpath('//div[@role="listbox"]/div[2]').click()

        # 点击月度右侧的按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//label[text()="年度"]/following-sibling::div[2]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
                )))
        driver.find_element_by_xpath(
            '//label[text()="年度"]/following-sibling::div[2]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
        ).click()

        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//div[@role="listbox"]/div[1]')))
        # 选自第一个条目
        driver.find_element_by_xpath('//div[@role="listbox"]/div[1]').click()

        # 搜索
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//button[text()="搜索"]')))
        driver.find_element_by_xpath('//button[text()="搜索"]').click()
        # driver.find_element_by_id("react-select-2--option-0").click()
        # driver.find_element_by_xpath('//button[text()="搜索"]').click()

        driver.switch_to.default_content()
        driver.find_element_by_class_name('u-button').click()
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_class_name('u-dropdown-menu-item')))
        driver.find_element_by_class_name('u-dropdown-menu-item').click()
예제 #34
0
input.send_keys('python')
btn = driver.find_element_by_id('su')
btn.click()
'''
'''操作选择栏select
from selenium.webdriver.support.ui import Select

driver.get('http://tieba.baidu.com/f/search/adv?red_tag=y2157203949')
sel = driver.find_element_by_name('sm')
selectTag = Select(sel)
# 根据索引选中
# selectTag.select_by_index(1)

# 根据值选中
# selectTag.select_by_value('2')

# 根据可视化文本选中
selectTag.select_by_visible_text('按相关性排序')
'''
'''行为链
'''
driver.get('https://www.baidu.com/')
input = driver.find_element_by_id('kw')
btn = driver.find_element_by_id('su')
actions = ActionChains(driver)
actions.move_to_element(input)  # 移动到input元素
actions.send_keys_to_element(input, 'python')  # 给input元素填充信息
actions.move_to_element(btn)  # 移动到btn元素
actions.click(btn)  # 点击btn元素
actions.perform()  # 执行所有行为
예제 #35
0
class Browser:
    def __init__(self):
        """
        Represents a Selenium browser object with added functions for Discord-specific purposes.
        No parameters; global settings are used from config.py.

        Methods
        -----------
        browser_login()
            Opens the browser to the Discord channel and logs in if necessary.
            Returns True if load successful.
            Raises TimeoutError if the page does not load.
            Raises ValueError if incorrect page loads.
        send_text(text)
            Send text to active channel.
        react_emoji(emoji, message_id)
            Searches and clicks an emoji button.
            Raises Exception if button was not found.
        roll(count)
            Sends the roll command for count number of times with 3 seconds between each roll.
        refresh()
            Refreshes the page.
        close()
            Closes the browser window.
        """
        # Selenium browser control here
        options = Options()
        options.add_argument('-headless')
        self.driver = webdriver.Firefox(executable_path=config.WEB_DRIVER_PATH, options=options)
        self.actions = ActionChains(self.driver)

        # Logging initialization
        self.logger = logging.getLogger(__name__)

    # Initiate browser
    def browser_login(self):
        self.logger.info('Browser thread started')
        self.logger.info('Attempting to open Discord in browser')
        self.driver.get(f'https://discord.com/channels/{config.SERVER_ID}/{config.CHANNEL_ID}')
        try:
            email = WebDriverWait(self.driver, 10).until(lambda x: x.find_element(By.NAME, 'email'))
        except TimeoutException:
            if f'{config.SERVER_ID}/{config.CHANNEL_ID}' not in self.driver.current_url:
                # No login screen, but wrong channel (some weird error)
                self.logger.critical('The channel did not load and no login was asked!')
                raise TimeoutError
        else:
            self.logger.info('Logging in with provided credentials (this may take up to 30 seconds)')
            email.send_keys(config.LOGIN_INFO[0])
            self.driver.find_element(By.NAME, 'password').send_keys(config.LOGIN_INFO[1])
            self.driver.find_element(By.XPATH, "//button[@type='submit']").click()
            try:
                # Wait for main screen
                WebDriverWait(self.driver, 30).until(lambda x: x.find_element(By.CLASS_NAME, 'slateTextArea-1Mkdgw'))
                if f'{config.SERVER_ID}/{config.CHANNEL_ID}' not in self.driver.current_url:
                    # Logged in, but wrong channel (some weird error)
                    raise ValueError
            except TimeoutException or NoSuchElementException:
                self.logger.critical('Login was unsuccessful. Please check LOGIN_INFO entry in config.py')
                raise TimeoutError
            except ValueError:
                self.logger.critical('Login was successful but the channel did not load')
                raise ValueError
            else:
                self.logger.info(f'Login successful to server {config.SERVER_ID} and channel {config.CHANNEL_ID}')
                return True

    def send_text(self, text: str):
        # For some reason, typing directly into the message box doesn't work
        # ActionChains must be used instead to type character by character
        self.actions = ActionChains(self.driver)
        self.logger.info(f'Sending text: {text}')
        try:
            message_box = WebDriverWait(self.driver, 1).until(
                lambda x: x.find_element(By.CLASS_NAME, 'slateTextArea-1Mkdgw'))
        except TimeoutException:
            self.logger.warning("Discord may have crashed, refreshing page")
            self.refresh()
            return self.send_text(text)
        self.actions.click(on_element=message_box)
        for char in text:
            self.actions.key_down(char)
            self.actions.key_up(char)
        self.actions.key_down(Keys.ENTER)
        self.actions.key_up(Keys.ENTER)
        self.actions.perform()

    def react_emoji(self, emoji: str, message_id: int):
        self.logger.info(f'Attempting to click emoji: {emoji}')
        xpath = f"//div[@id='chat-messages-{message_id}']//div[@aria-label='{emoji}, press to react']"
        try:
            # Get div containing emoji
            emoji_div = WebDriverWait(self.driver, 7).until(lambda x: x.find_element(By.XPATH, xpath))
            # Get current count
            count = int(emoji_div.find_element(By.XPATH, "//div[@class='reactionCount-2mvXRV']").text)
            # Click emoji
            # WebElement.click() breaks for some reason, use javascript instead
            self.driver.execute_script('arguments[0].click();', emoji_div)

            # Check new count
            try:
                WebDriverWait(self.driver, 1) \
                    .until_not(lambda x:
                               int(x.find_element(By.XPATH,
                                                  f"{xpath}//div[@class='reactionCount-2mvXRV']").text) > count)
            except TimeoutException:  # No increase in count
                self.logger.warning('Emoji was found, but unsuccessfully clicked')
                raise TimeoutError
            else:
                self.logger.info('Emoji successfully clicked')
        except TimeoutException or NoSuchElementException:
            self.logger.critical('Unable to find the emoji to click')
            raise TimeoutError

    def roll(self, count: int):
        """
        Rolls for count number of times.
        """
        for _ in range(count):
            self.send_text(f'{config.COMMAND_PREFIX}{config.ROLL_COMMAND}')
            time.sleep(3)  # Sleep for 3 seconds between roll commands

    def refresh(self):
        self.driver.refresh()
        WebDriverWait(self.driver, 10).until(
            lambda x: x.find_element(By.CLASS_NAME, 'slateTextArea-1Mkdgw'))

    def close(self):
        self.driver.close()
예제 #36
0
    def resize_editor(self, editor):
        '''ensure that the editor is not covering the library
        (or else we cannot drag things from it!)'''
        browser = self.browser

        page_width = browser.get_window_size()['width']

        lib_tab = self('library_tab').find_element_by_xpath('..')
        lib_width = lib_tab.size['width']
        lib_position = lib_tab.location['x']

        dialog_title = editor('dialog_title').find_element_by_xpath('../..')
        dialog_width = dialog_title.size['width']
        dialog_position = dialog_title.location['x']

        # how much overlap do we have?
        overlap = lib_position - (dialog_position + dialog_width)

        if overlap < 0:  # we are overlapping
            # check to see if we have enough room to move out of the way
            if page_width < dialog_width + lib_width:
                # not enough, need to rezize the editor

                # look for the resize handle
                sibblings = dialog_title.find_elements_by_xpath('../../div')
                handle = None
                for sib in sibblings:
                    if "ui-resizable-se" in sib.get_attribute('class'):
                        handle = sib

                # do the resizing
                chain = ActionChains(browser)
                chain.click_and_hold(handle)
                # we can resize editor down to 425px, any less and we cover drop targets
                chain.move_by_offset(450 - dialog_width, 0).perform()
                # must click because release is not working. why? I do not know.
                chain.click().perform()
                chain.release(None).perform()

                # recalculate the overlap
                dialog_title = editor('dialog_title').find_element_by_xpath(
                    '../..')
                dialog_width = dialog_title.size['width']
                dialog_position = dialog_title.location['x']
                overlap = lib_position - (dialog_position + dialog_width)

            # We are good, move out!
            chain = ActionChains(browser)
            chain.click_and_hold(editor('dialog_title').element)
            chain.move_by_offset(overlap, 0).perform()
            # must click because release is not working. why? I do not know.
            chain.click().perform()
            chain.release(None).perform()

            # recalculate the overlap
            dialog_title = editor('dialog_title').find_element_by_xpath(
                '../..')
            dialog_width = dialog_title.size['width']
            dialog_position = dialog_title.location['x']
            overlap = lib_position - (dialog_position + dialog_width)

            if overlap < 0:
                # we still have a problem.
                eq(
                    True, False,
                    "Could not move or rezise the editor dialog so it is not "
                    "overlapping the library. The browser window is too small")
예제 #37
0
def submit_code(username: str, password: str, problem_to_solve: str,
                sock: socket.socket):
    global browser
    try:
        # Clear Browser Cookies
        browser.delete_all_cookies()

        print("正在获取代码......")
        browser.get('https://gitee.com/xz2000/SJTU-OJ/raw/master/Code/' +
                    problem_to_solve + '.cpp')
        print('代码获取成功!')
        code_to_input: str = browser.find_element_by_xpath(
            '/html/body/pre').text
        print(code_to_input)

        if (code_to_input.startswith("404:")):
            print('代码获取失败,正在向用户发送信息...')
            logging.error('未找到代码')
            try:
                server_utils.send_msg(sock, "toast:抱歉,服务器没有当前题目的代码")
                print('发送信息成功!')
            except:
                print('向用户发送信息失败!')
            return

        browser.get("https://acm.sjtu.edu.cn/OnlineJudge")
        input_username = browser.find_element(By.NAME, 'username')
        input_password = browser.find_element(By.NAME, 'password')
        btn_login = browser.find_element(By.NAME, 'action')

        actions = ActionChains(browser)
        actions.send_keys_to_element(input_username, username)
        actions.send_keys_to_element(input_password, password)
        actions.click(btn_login)
        actions.perform()

        try:
            browser.get("https://acm.sjtu.edu.cn/OnlineJudge/submit")

            input_problem = browser.find_element(By.NAME, 'problem')
            input_code = browser.find_element(By.NAME, 'code')
            btn_submit = browser.find_element(
                By.XPATH, '//*[@id="wrap"]/div/form/fieldset/div[4]/button')
        except Exception as err:
            logging.error('提交出现异常(账户密码错误)' + err.__str__())
            print('提交出现异常,账户密码错误')
            try:
                server_utils.send_msg(sock, "toast:您的密码有误,请检查您的账户密码")
                print('发送信息成功!')
            except:
                print('向用户发送信息失败!')
            return

        actions = ActionChains(browser)
        actions.send_keys_to_element(input_problem, problem_to_solve)
        actions.send_keys_to_element(input_code, code_to_input)
        actions.click(btn_submit)
        actions.perform()
        print('提交已经成功,正在向用户发送信息')
        logging.info('代码获取成功')
        try:
            server_utils.send_msg(sock, "toast:提交已经成功,请关注评测结果")
            print('发送信息成功!')
        except:
            print('向用户发送信息失败!')
    except Exception as err:
        print('抱歉!出现错误')
        print('正在向用户发送信息...')
        logging.error('代码服务异常' + err.__str__())
        try:
            server_utils.send_msg(sock, "toast:代码提交或拉取服务出现错误,请稍后再试")
            print('发送信息成功!')
        except:
            print('向用户发送信息失败!')
        # Restart Chrome
        # browser.close()
        option = webdriver.ChromeOptions()
        option.add_argument('--headless')
        option.add_argument('--no-sandbox')
        browser = webdriver.Chrome(options=option)
        logging.info('提交服务已经重启')
    def runTest(self):
        driver = self.getDriver()
        param = self.param
        tool = utils
        driver.refresh()
        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()
        sleep(1)
        # 进入财务管理
        driver.find_element_by_xpath('//*[text()="财务管理"]').click()
        sleep(1)
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="费用管理"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(1)
        # 进入二级节点
        menu3 = driver.find_element_by_css_selector(
            'li[class="bottomBar"][title="单据可用项目设置"]')
        actions.move_to_element(menu3)
        actions.click(menu3)
        actions.perform()

        sleep(2)
        titleName = driver.find_element_by_css_selector(
            '#home_header > div > div.tab--38iB- > ul > li > p').get_attribute(
                'title')
        assert u"单据可用项目设置" in titleName, u"页面源码中不存在该关键字!"
        sleep(2)
        iframe = driver.find_element_by_id('FICO_DJKYXMSZ')
        driver.switch_to.frame(iframe)

        # 新增
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(driver.find_element_by_xpath('//*[text()="新增"]')))
        driver.find_element_by_xpath('//*[text()="新增"]').click()

        # 点击取消
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(driver.find_element_by_xpath('//*[text()="取消"]')))
        driver.find_element_by_xpath('//*[text()="取消"]').click()

        # 新增
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(driver.find_element_by_xpath('//*[text()="新增"]')))
        driver.find_element_by_xpath('//*[text()="新增"]').click()

        # 输入单据类型
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//span[text()="单据类型"]/parent::div/following-sibling::div//input[1]'
                )))
        driver.find_element_by_xpath(
            '//span[text()="单据类型"]/parent::div/following-sibling::div//input[1]'
        ).click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
                )))
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
        ).click()

        # 输入限制档案
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//span[text()="限制档案"]/parent::div/following-sibling::div//input[1]'
                )))
        driver.find_element_by_xpath(
            '//span[text()="限制档案"]/parent::div/following-sibling::div//input[1]'
        ).click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
                )))
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
        ).click()

        # 输入已选项目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//span[text()="已选项目"]/parent::div/following-sibling::div//input[1]'
                )))
        driver.find_element_by_xpath(
            '//span[text()="已选项目"]/parent::div/following-sibling::div//input[1]'
        ).click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
                )))
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
        ).click()

        # 点击保存
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//button[text()="确定"]')))
        driver.find_element_by_xpath('//button[text()="确定"]').click()

        # 断言
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]'
                )))
        ele = driver.find_element_by_xpath(
            '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]'
        )
        self.assertIsNotNone(ele)

        # 点击编辑按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]//span[text()="编辑"]'
                )))
        driver.find_element_by_xpath(
            '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]//span[text()="编辑"]'
        ).click()

        # 点击保存
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//button[text()="确定"]')))
        driver.find_element_by_xpath('//button[text()="确定"]').click()

        # 点击删除按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]//span[text()="删除"]'
                )))
        driver.find_element_by_xpath(
            '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]//span[text()="删除"]'
        ).click()

        # 点击确定按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//button[@class="ant-btn ant-btn-danger"]')))
        driver.find_element_by_xpath(
            '//button[@class="ant-btn ant-btn-danger"]').click()

        driver.switch_to.default_content()
        driver.find_element_by_class_name('u-button').click()
        sleep(1)
        driver.find_element_by_class_name('u-dropdown-menu-item').click()
예제 #39
0
'''
Created on Oct 12, 2017

@author: Dell lap
'''
from drivers import driver
from selenium.webdriver import ActionChains
import time
driver.get("http://localhost/mystore")
# get desktop element
# //a[contains(text(), 'Desktops')]
desktop = driver.find_element_by_xpath("//a[contains(text(), 'Desktops')]")
# create actions
action = ActionChains(driver)
# move to the element => mouse move != mouse click
action.move_to_element(desktop)
action.perform()
action.click(driver.find_element_by_partial_link_text("PC"))
action.perform()
#perform()
# perform is necessary

time.sleep(5)
driver.quit()
예제 #40
0
    def runTest(self):
        driver = self.getDriver()
        param = self.param
        tool = utils
        driver.refresh()

        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()

        menu2 = driver.find_element_by_css_selector('span[title="组织管理"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(1)
        # 进入二级节点
        menu3 = driver.find_element_by_css_selector('li[title="职级"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu3)
        actions.click(menu3)
        actions.perform()
        assert u"职级" in driver.page_source, u"页面源码中不存在该关键字!"
        sleep(3)

        # 切换iframe
        iframe = driver.find_element_by_id('HRSZ020050')
        driver.switch_to.frame(iframe)
        # sleep(5)

        # 新增
        driver.find_element_by_id('ranklist|btnAdd').click()
        # 职级编号
        driver.find_element_by_xpath('//label[text()="职级编号"]/../..//input').send_keys("ZJ001")
        # 职级名称
        driver.find_element_by_xpath('//label[text()="职级名称"]/../..//input').send_keys("高级测试")
        # 职务类别
        driver.find_element_by_xpath('//label[text()="职务类别"]/../..//span[@class="ant-input-suffix"]').click()
        sleep(1)
        driver.find_element_by_xpath('//div[@id="bd_dutyType"]//label//input').click()
        driver.find_element_by_xpath('//span[text()="确 定"]').click()
        # 最高职等
        driver.find_element_by_xpath('//label[text()="最高职等"]/../..//span[@class="ant-input-suffix"]').click()
        sleep(1)
        driver.find_element_by_xpath('//div[@id="bd_graderef"]//label//input').click()
        driver.find_element_by_xpath('//div[6]//span[text()="确 定"]').click()
        # 保存
        driver.find_element_by_id('rank|btnSave').click()

        # 新增
        driver.find_element_by_id('ranklist|btnAdd').click()
        # 职级编号
        driver.find_element_by_xpath('//label[text()="职级编号"]/../..//input').send_keys("ZJ002")
        # 职级名称
        driver.find_element_by_xpath('//label[text()="职级名称"]/../..//input').send_keys("初级测试")
        # 职务类别
        driver.find_element_by_xpath('//label[text()="职务类别"]/../..//span[@class="ant-input-suffix"]').click()
        driver.find_element_by_xpath('//div[@id="bd_dutyType"]//label//input').click()
        driver.find_element_by_xpath('//span[text()="确 定"]').click()
        # 最低职等
        driver.find_element_by_xpath('//label[text()="最低职等"]/../..//span[@class="ant-input-suffix"]').click()
        sleep(1)
        driver.find_element_by_xpath('//div[@id="bd_graderef"]//label//input').click()
        driver.find_element_by_xpath('//div[6]//span[text()="确 定"]').click()
        # 保存并新增
        driver.find_element_by_id('rank|btnSaveAndAdd').click()
        # 取消
        driver.find_element_by_id('rank|btnAbandon').click()

        # 启用/停用
        driver.find_element_by_xpath('//div[text()="ZJ001"]').click()
        ActionChains(driver).move_to_element(driver.find_element_by_xpath('//span[text()="启 用"]/../..//i')).perform()
        driver.find_element_by_xpath('//li[text()="启用"]').click()
        driver.find_element_by_xpath('//div[text()="名称/编码"]').click()

        # 编辑
        ActionChains(driver).move_to_element(driver.find_element_by_xpath('//div[text()="ZJ001"]')).perform()
        driver.find_element_by_xpath('//a[text()="编辑"]').click()
        # 保存
        driver.find_element_by_id('rank|btnSave').click()

        # 删除
        driver.find_element_by_xpath('//div[text()="ZJ002"]').click()
        driver.find_element_by_id('ranklist|btnBatchDelete').click()
        sleep(3)
        driver.find_element_by_xpath('//div[@class="ant-confirm-btns"]//span[text()="确 定"]').click()

        # 搜索
        driver.find_element_by_xpath('//div[text()="名称/编码"]/..//input').send_keys("ZJ001")
        driver.find_element_by_xpath('//span[text()="搜 索"]').click()
        sleep(5)

        # 返回主窗体
        driver.switch_to.default_content()

        # 关闭页签
        driver.find_element_by_css_selector('button[class="u-button"]').click()
        driver.find_element_by_css_selector('li[title="关闭全部页签"]').click()
예제 #41
0
    def runTest(self):
        driver = self.getDriver()
        driver.implicitly_wait(30)
        param = self.param
        tool = utils
        driver.refresh()
        # driver.find_element_by_xpath('//*[@id="_dropdown_popcontainer"]/div/i').click()
        # driver.find_element_by_xpath('//*[@id="home_header"]//div[text()="UI测试专属"]').click()
        # driver.find_element_by_xpath(
        #     '//button[@class="u-button btn__style___37bsb u8c_primary__style___RFibc  btn__style___20DQM "]').click()
        # sleep(2)
        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()
        sleep(2)
        # 进入社交协同
        driver.find_element_by_xpath('//*[text()="人力资源"]').click()
        sleep(2)
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="薪资核算"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(2)
        # 进入二级节点
        driver.find_element_by_xpath('//li[@title="薪资标准"]').click()
        sleep(2)
        # 跳转劳动合同签订iframe
        iframe = driver.find_element_by_id('HRXC010050')
        # # driver.switch_to.frame(iframe)
        SwitchTo(driver).frame(iframe)
        sleep(2)

        # 点击新增薪资标准按钮
        driver.find_element_by_xpath('//i[@class="el-icon-plus fn"]').click()
        sleep(2)
        num = random.randint(100, 999)
        code = 'GBM{}'.format(num)
        # 输入标准表编码
        driver.find_element_by_xpath('//label[text()="标准表编码"]/following-sibling::div//input').send_keys(code)

        # 输入标准表名称
        num1 = random.randint(100, 999)
        name = 'GBB{}'.format(num1)
        driver.find_element_by_xpath('//label[text()="标准表名称"]/following-sibling::div//input').send_keys(name)

        # 点击对应薪资项目右侧按钮
        driver.find_element_by_xpath(
            '//label[text()="对应薪资项目"]/following-sibling::div//span[@class="el-input__suffix"]').click()

        # 选择条目信息
        driver.find_element_by_xpath('//span[text()="{}"]/parent::span'.format(Name.names)).click()

        # 点击选择项目信息
        driver.find_element_by_xpath('//div[@class="el-table__body-wrapper is-scrolling-none"]/table').click()

        # 点击确定按钮
        driver.find_element_by_xpath('//div[@class="op-button"]//button[2]').click()
        sleep(1)

        # 输入薪资级数
        driver.find_element_by_xpath('//label[text()="薪级数"]/following-sibling::div//input').send_keys("2")

        # 输入薪资档数
        driver.find_element_by_xpath('//label[text()="薪档数"]/following-sibling::div//input').send_keys("2")

        # 点击下一步按钮
        driver.find_element_by_xpath('//div[@class="bottom-fn"]//button[3]').click()
        sleep(2)

        # 输入薪资信息
        driver.find_element_by_xpath(
            '//div[@class="el-table__body-wrapper is-scrolling-none"]//tr[1]/td[2]/div').click()
        driver.find_element_by_xpath('//div[@class="el-input"]/input').send_keys(8000)

        driver.find_element_by_xpath(
            '//div[@class="el-table__body-wrapper is-scrolling-none"]//tr[1]/td[3]/div').click()
        driver.find_element_by_xpath('//div[@class="el-input"]/input').send_keys(10000)

        driver.find_element_by_xpath(
            '//div[@class="el-table__body-wrapper is-scrolling-none"]//tr[2]/td[2]/div').click()
        driver.find_element_by_xpath('//div[@class="el-input"]/input').send_keys(15000)

        driver.find_element_by_xpath(
            '//div[@class="el-table__body-wrapper is-scrolling-none"]//tr[2]/td[3]/div').click()
        driver.find_element_by_xpath('//div[@class="el-input"]/input').send_keys(20000)

        # 点击保存按钮
        driver.find_element_by_xpath('//div[@class="in-bottom"]//button[4]').click()
        sleep(2)

        # 点击启用版本
        driver.find_element_by_xpath('//div[@class="btn-wrap"]//button[5]').click()

        # 点击左侧的时间按钮
        driver.find_element_by_xpath(
            '//label[text()="生效日期"]/ancestor::div[@role="dialog"]//i[@class="el-input__icon el-icon-date"]').click()

        # 点击今天
        driver.find_element_by_xpath('//table[@class="el-date-table"]//td[@class="available today"]').click()

        # 点击确定按钮
        driver.find_element_by_xpath('//label[text()="生效日期"]/ancestor::div[@role="dialog"]//button[2]').click()
        sleep(1)
        self.assertEqual("操作成功!", driver.find_element_by_xpath('//p[text()="操作成功!"]').text)

        # 点击取消启用
        driver.find_element_by_xpath('//div[@class="main-header"]//button[3]').click()
        sleep(1)
        self.assertEqual("操作成功!", driver.find_element_by_xpath('//p[text()="操作成功!"]').text)
        sleep(2)
        # 关闭当前页面
        driver.switch_to.default_content()
        sleep(1)
        driver.find_element_by_xpath('//*[@id="home_header"]/div/div[3]/ul/li/div').click()
예제 #42
0
    def runTest(self):
        driver = self.getDriver()
        driver.implicitly_wait(30)
        param = self.param
        tool = utils
        driver.refresh()
        # driver.find_element_by_xpath('//*[@id="_dropdown_popcontainer"]/div/i').click()
        # driver.find_element_by_xpath('//*[@id="home_header"]//div[text()="UI测试专属"]').click()
        # driver.find_element_by_xpath(
        #     '//button[@class="u-button btn__style___37bsb u8c_primary__style___RFibc  btn__style___20DQM "]').click()
        # sleep(2)
        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()
        sleep(2)
        # 进入社交协同
        driver.find_element_by_xpath('//*[text()="人力资源"]').click()
        sleep(2)
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="假勤管理"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(2)
        # 进入二级节点
        driver.find_element_by_xpath('//li[@title="考勤规则"]').click()

        sleep(2)
        # 跳转劳动合同签订iframe
        iframe = driver.find_element_by_id('HRJQ020010')
        # # driver.switch_to.frame(iframe)
        SwitchTo(driver).frame(iframe)
        sleep(2)
        source = driver.page_source
        str1 = 'new规则'
        # 点击新建规则按钮
        driver.find_element_by_xpath(
            '//*[@id="attendance-rules-add"]//button/span[text()="新建规则"]'
        ).click()
        sleep(3)
        # 点击组织右侧按钮
        driver.find_element_by_xpath(
            '//div[@class="el-autocomplete reference-com formInput"]/div/span/span/span/i[2]'
        ).click()
        sleep(3)

        # 选中组织
        driver.find_element_by_xpath(
            '//*[@id="ref-tree-container"]/div/div/div/div[1]/div/div/div[1]/div[2]/div[1]/div/span[2]/span'
        ).click()

        # 点击确认
        driver.find_element_by_xpath(
            '//div[@class="el-dialog__wrapper custom-ref-dialog"]//button[@class="el-button el-button--primary"]'
        ).click()

        # 输入规则名称
        num = random.randint(10000, 99999)
        str_regular = "new规则{}".format(num)

        driver.find_element_by_xpath(
            '//label[text()="规则名称"]/parent::div//div[@class="el-input"]/input'
        ).send_keys(str_regular)

        #  点击组织按钮
        driver.find_element_by_xpath(
            '//div[@class="el-autocomplete reference-com"]//span[text()="选组织"]'
        ).click()
        sleep(3)
        # 选择北京仓储中心
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//span[text()="仓储中心-北京"]').click()

        # 点击确定按钮
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//button[@class="el-button el-button--primary"]'
        ).click()

        # 点击人员
        driver.find_element_by_xpath(
            '//div[@class="el-autocomplete reference-com"]//span[text()="选人员"]'
        ).click()
        sleep(3)

        # 选择人员
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//span[text()="仓储中心-北京"]').click()
        sleep(2)
        # 点击全选按钮
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//div[@style="height: 340px;"]//div[text()="名称"]//ancestor::tr//span[@class="el-checkbox__input"]'
        ).click()

        # 点击确定按钮
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//button[@class="el-button el-button--primary"]'
        ).click()

        # 点击班次,选择班次
        driver.find_element_by_xpath(
            '//div[@class="el-autocomplete reference-com"]//span[text()="选班次"]'
        ).click()
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//tbody/tr[1]').click()

        # 点击确定按钮
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//button[@class="el-button el-button--primary"]'
        ).click()

        # 点击添加地理位置
        driver.find_element_by_xpath(
            '//div[@class="el-autocomplete reference-com"]//span[text()="添加地理位置"]'
        ).click()

        #  选择一项
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//tbody/tr[1]//span[@class="el-checkbox__inner"]'
        ).click()

        # 点击确定按钮
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//button[@class="el-button el-button--primary"]'
        ).click()

        # 点击保存
        driver.find_element_by_xpath(
            '//*[@id="attendance-rules-add-edit"]//button[@class="el-button el-button--primary"]'
        ).click()
        sleep(2)
        # 判断是否是第二次运行
        if source.find(str1) >= 0:
            driver.find_element_by_xpath(
                '//div[@class="el-message-box__btns"]/button[2]').click()
        # 组织没有被引用时,不需要覆盖。
        # sleep(2)
        # # 点击覆盖按钮
        # driver.find_element_by_xpath('//div[@class="el-message-box"]//button[@class="el-button el-button--default el-button--small el-button--primary "]').click()

        sleep(3)
        # 断言
        self.assertIn(str_regular, driver.page_source)

        # 关闭当前页面
        driver.switch_to.default_content()
        sleep(1)
        driver.find_element_by_xpath(
            '//*[@id="home_header"]/div/div[3]/ul/li/div').click()
예제 #43
0
def start_crawl(journal, start_year, end_year, output_file):
    global type_browser, url, WAIT_SECONDS, MAX_NUM_PAPERS
    print('Start crawling publish number of journal {} during {} - {}'.format(
        journal, start_year, end_year))

    browser = get_browser(type_browser, headless=False)
    browser.get(url)

    # 等待高级检索按键加载完成并点击
    try:
        a_high_search = WebDriverWait(browser, WAIT_SECONDS).until(
            EC.element_to_be_clickable((By.LINK_TEXT, '高级检索')))
    except TimeoutException as e:
        print('Timeout during waiting for loading of high search buttom.')
        browser.quit()
        return False
    a_high_search.click()
    time.sleep(1)

    # 切换到最新打开的窗口
    windows = browser.window_handles
    browser.switch_to.window(windows[-1])

    # 找到文献来源标签,用于后面判断点击刷新完成
    try:
        span_src = browser.find_element_by_xpath(
            '//*[@id="gradetxt"]/dd[3]/div[2]/div[1]/div[1]/span')
    except NoSuchElementException as e:
        print(str(e))
        browser.quit()
        return False

    # 等待学术期刊按键加载完成并点击
    try:
        span_journal = WebDriverWait(browser, WAIT_SECONDS).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 '//ul[@class="doctype-menus keji"]/li[@data-id="xsqk"]/a/span'
                 )))
    except TimeoutException as e:
        print('Timeout during waiting for loading of journal buttom.')
        browser.quit()
        return False
    browser.execute_script('arguments[0].click();', span_journal)

    # 通过文献来源标签的过期判断刷新完成
    try:
        WebDriverWait(browser, WAIT_SECONDS).until(EC.staleness_of(span_src))
    except TimeoutException as e:
        print('Timeout during refresh after clicking journal buttom')
        browser.quit()
        return False

    # 等待期刊名称输入框加载完成
    try:
        input_journal = WebDriverWait(browser, WAIT_SECONDS).until(
            EC.presence_of_element_located(
                (By.XPATH, '//*[@id="gradetxt"]/dd[3]/div[2]/input')))
    except TimeoutException as e:
        print('Timeout during waiting for input box for jounral name.')
        browser.quit()
        return False
    input_journal.send_keys(journal)  # 输入期刊名
    time.sleep(1)

    # 找到起始年输入框并输入起始年
    try:
        input_start_year = browser.find_element_by_xpath(
            '//input[@placeholder="起始年"]')
    except NoSuchElementException as e:
        print(str(e))
        browser.quit()
        return False
    input_start_year.send_keys(start_year)

    # 找到结束输入框并输入结束年
    try:
        input_end_year = browser.find_element_by_xpath(
            '//input[@placeholder="结束年"]')
    except NoSuchElementException as e:
        print(str(e))
        browser.quit()
        return False
    input_end_year.send_keys(end_year)

    # 找到检索键并点击
    try:
        input_search = browser.find_element_by_xpath('//input[@value="检索"]')
    except NoSuchElementException as e:
        print(str(e))
        browser.quit()
        return False
    input_search.click()

    # 根据搜索结果总数标签的出现判断页面是否刷新完成
    try:
        em_total = WebDriverWait(browser, WAIT_SECONDS).until(
            EC.visibility_of_element_located(
                (By.XPATH, '//*[@id="countPageDiv"]/span[1]/em')))
    except TimeoutException as e:
        print('Timeout during waiting for paper number cell.')
        browser.quit()
        return False
    expected_num = str2int(em_total.text)

    # 找到发表年度
    try:
        dt_year = WebDriverWait(browser, WAIT_SECONDS).until(
            EC.element_to_be_clickable((By.XPATH, '//dt[@groupitem="发表年度"]')))
    except TimeoutException as e:
        print(
            'Timeout during waiting for loading of publish years list. Journal: {}, year: {} - {}.'
            .format(journal, start_year, end_year))
        browser.quit()
        return False

    # 将鼠标移动到发表年度,若发表年度被折叠,则点击之
    action = ActionChains(browser).move_to_element(dt_year)
    dt_year_parent = browser.find_element_by_xpath(
        '//dt[@groupitem="发表年度"]/..')
    if dt_year_parent.get_attribute('class') == 'is-up-fold off':
        action.click().perform()  # 点击发表年度

    # 让鼠标悬浮在发表年度的部分展开列表上,使其完全展开
    try:
        div_lst = WebDriverWait(browser, WAIT_SECONDS).until(
            EC.visibility_of_element_located(
                (By.XPATH, '//dd[@tit="发表年度"]/div')))
    except TimeoutException as e:
        print(
            'Timeout during waiting for display of complete publish years. Journal: {}, year: {} - {}.'
            .format(journal, start_year, end_year))
        browser.quit()
        return False
    ActionChains(browser).move_to_element(div_lst).perform()

    info = OrderedDict()
    info['期刊名称'] = journal
    actual_num = 0
    timeout = False
    # 找到目标范围内的年份的发表数量
    for year in range(start_year, end_year + 1):
        if not timeout or year == 2014:
            try:
                span = WebDriverWait(browser, WAIT_SECONDS).until(
                    EC.visibility_of_element_located((
                        By.XPATH,
                        '//input[@type="checkbox" and @text="{0}" and @value="{0}"]/following-sibling::span'
                        .format(str(year)))))
            except TimeoutException as e:
                print(
                    'No paper found for journal {0} in year {1}. Journal: {0}, year: {2} - {3}.'
                    .format(journal, year, start_year, end_year))
                info[str(year)] = 0
                timeout = True
                continue
        else:
            try:
                span = browser.find_element_by_xpath(
                    '//input[@type="checkbox" and @text="{0}" and @value="{0}"]/following-sibling::span'
                    .format(str(year)))
            except NoSuchElementException as e:
                print(str(e))
                info[str(year)] = 0
                continue
        #print('year: {}, num: {}'.format(year, span.text))
        num = int(span.text[1:-1])
        info[str(year)] = num
        actual_num += num

    # 检验九年发表数量总和是否等于筛选结果数量
    if actual_num != expected_num:
        print(
            'Total number of papers conflict, expected number: {}, actual number: {}. Journal: {}, year: {} - {}.'
            .format(expected_num, actual_num, journal, start_year, end_year))
        browser.quit()
        return False

    info['总数'] = expected_num
    # 将爬取结果保存到excel中
    df = pd.DataFrame(data=[info])
    df.to_excel(output_file)

    browser.quit()
    print(
        'Finish crawling publish number of journal {} during {} - {}, expected number of papers: {}'
        .format(journal, start_year, end_year, expected_num))
    return True
예제 #44
0
def set_fund_condition(chrome_driver):
    print('打开了基金筛选器')

    # 根据货币基金筛选条件,进行选择筛选条件 并选中
    huobiCheckBox = chrome_driver.find_element_by_id('ctl00_cphMain_cblCategory_15')
    huobiCheckBox.click()
    print('选择货币基金筛选条件成功')

    # 选择基金规模 range 并设置为100 - 200+
    ziChanRange = chrome_driver.find_element_by_id('fs_slider_tna')
    # 给浏览器添加事件
    action = ActionChains(chrome_driver)
    # 对滑块按住鼠标左键不放
    action.move_to_element(ziChanRange)
    action.move_by_offset(0, 0)
    action.click().perform()
    sleep(1)
    action.reset_actions()
    action.move_by_offset(45, 0)  # 以上一次移动为基础
    action.click().perform()
    sleep(1)
    action.reset_actions()
    action.move_by_offset(45, 0) # 以上一次移动为基础
    action.click().perform()
    print('选择基金规模筛选条件成功')

    # # 循环
    # for i in range(2):
    #     print(i)
    #     try:
    #         # 循环的移东滑块,当滑块移动到末尾的时候会发生错误,捕获异常
    #         action.move_by_offset(1, 0)
    #     except:
    #         break
    #     # 继续执行事件
    #     action = ActionChains(chrome_driver)
    #     # 每次滑块移动的间歇时间
    #     sleep(1)
    action.release()

    # 业绩总回报 选择 今年以来、三个月、六个月、一年、两年、三年、五年 都>=同类平均
    thisYear = chrome_driver.find_element_by_id('ctl00_cphMain_ucPerformance_rbYtd1')
    thisYear.click()

    threeMonth = chrome_driver.find_element_by_id('ctl00_cphMain_ucPerformance_rbM31')
    threeMonth.click()

    sixMonth = chrome_driver.find_element_by_id('ctl00_cphMain_ucPerformance_rbM61')
    sixMonth.click()

    oneYear = chrome_driver.find_element_by_id('ctl00_cphMain_ucPerformance_rbY11')
    oneYear.click()

    twoYear = chrome_driver.find_element_by_id('ctl00_cphMain_ucPerformance_rbY21')
    twoYear.click()

    threeYear = chrome_driver.find_element_by_id('ctl00_cphMain_ucPerformance_rbY31')
    threeYear.click()

    fiveYear = chrome_driver.find_element_by_id('ctl00_cphMain_ucPerformance_rbY51')
    fiveYear.click()
    print('选择基金业绩总回报筛选条件成功')

    # 筛选
    chrome_driver.find_element_by_id('ctl00_cphMain_btnGo').click()
    print('开始筛选')
from selenium import webdriver
from selenium.webdriver import ActionChains
import time


driver = webdriver.Chrome()
driver.get("https://www.imdb.com/")
time.sleep(3)
eleMenuShowtimes = driver.find_element_by_id("navTitleMenu")

action_chains = ActionChains(driver)
action_chains.move_to_element(eleMenuShowtimes)
time.sleep(3)
action_chains.click(driver.find_element_by_link_text("In Theaters"))
action_chains.perform()
time.sleep(3)
assert  "New Movies In Theaters" in driver.title

driver.quit()
from selenium import webdriver
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("http://rentvehicles.multicompetition.com/")
driver.implicitly_wait(10)

enterEmail = driver.find_element(By.ID, 'email')
enterPassword = driver.find_element(By.ID, 'password')
enterLoginBtn = driver.find_element_by_id("btnLogin")

act_chains = ActionChains(driver)
act_chains.send_keys_to_element(enterEmail, '*****@*****.**').perform()
act_chains.send_keys_to_element(enterPassword, 'admin@123').perform()
act_chains.click(enterLoginBtn).perform()
예제 #47
0
    def Run(self, isClear):
        for info in self.listCmd:
            if info.isWaiting:
                if self.IsElementExist(info.cmd):
                    item = self.driver.find_element(By.XPATH, info.cmd)
                else:
                    # waiting
                    while True:
                        time.sleep(1)
                        print("waiting info.cmd=", info.cmd)
                        if self.IsElementExist(info.cmd):
                            item = self.driver.find_element(By.XPATH, info.cmd)
                            break

            else:
                item = info.item
                if item == None:
                    item = self.driver.find_element(By.XPATH, info.cmd)
                    info.item = item

            if info.type == CmdType.CLICK:
                # self.driver.execute_script("arguments[0].click();", item)
                item.click()
            if info.type == CmdType.CLICK_SCRIPT:
                # 有些item.click() 会报InvalidArgumentException: Message: invalid argument
                self.driver.execute_script("arguments[0].click();", item)

            if info.type == CmdType.CLICK_Action:
                # 有些item.click() 无响应 用这个鼠标模拟点击
                action = ActionChains(self.driver)
                action.click(item).perform()

            if info.type == CmdType.INPUT:
                item.clear()
                item.send_keys(info.value)
                # item.clear()
                # item.send_keys(info.value)
                # item.text = info.value

            if info.type == CmdType.INPUT_CLEAR:
                item.clear()

            if info.type == CmdType.ENTER:
                item.send_keys(Keys.ENTER)
            if info.type == CmdType.CTR_V:
                item.send_keys(Keys.CONTROL, "v")

            if info.type == CmdType.CLICK_List_ALL:
                list = self.driver.find_elements(By.XPATH, info.cmd)
                for item in list:
                    item.click()

            if info.type == CmdType.CLICK_List_Item:
                list = self.driver.find_elements(By.XPATH, info.cmd)
                item = list[info.index]
                if info.type2 == CmdType.CLICK:
                    item.click()
                if info.type2 == CmdType.CLICK_SCRIPT:
                    self.driver.execute_script("arguments[0].click();", item)
                if info.type2 == CmdType.CLICK_Action:
                    action = ActionChains(self.driver)
                    action.click(item).perform()

            time.sleep(info.delay)

        if isClear:
            self.Clear()
예제 #48
0
    def runTest(self):
        driver = self.getDriver()
        param = self.param
        tool = utils
        driver.refresh()
        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()
        sleep(1)
        # 进入财务管理
        driver.find_element_by_xpath('//*[text()="财务管理"]').click()
        sleep(1)
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="财务公共"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(1)
        # 进入二级节点
        menu3 = driver.find_element_by_css_selector(
            'li[class="bottomBar"][title="科目表"]')
        actions.move_to_element(menu3)
        actions.click(menu3)
        actions.perform()

        sleep(2)
        titleName = driver.find_element_by_css_selector(
            '#home_header > div > div.tab--38iB- > ul > li > p').get_attribute(
                'title')
        assert u"科目表" in titleName, u"页面源码中不存在该关键字!"
        sleep(2)
        iframe = driver.find_element_by_id('setting_subjectchart')
        driver.switch_to.frame(iframe)
        sleep(1)

        # 点击新增
        driver.find_element_by_xpath(
            '//button[@class="btn btn-primary"]').click()
        sleep(1)
        # 点击会计主体按钮
        driver.find_element_by_xpath(
            '//label[text()="会计主体"]/following-sibling::div//span[@class="input-group-addon cursor-style"]'
        ).click()

        # 点击条目
        driver.find_element_by_xpath('//span[text()="企业账号级"]').click()

        # 输入编码
        num = random.randint(999, 10000)
        code = 'BM{}'.format(num)
        driver.find_element_by_xpath(
            '//label[text()="编码"]/following-sibling::div//input').send_keys(
                code)

        # 输入名称
        num1 = random.randint(999, 10000)
        name = '名称{}'.format(num1)
        driver.find_element_by_xpath(
            '//label[text()="名称"]/following-sibling::div//input').send_keys(
                name)

        # 点击会计要素表右侧按钮
        driver.find_element_by_xpath(
            '//label[text()="会计要素表"]/following-sibling::div//span[@class="input-group-addon cursor-style"]'
        ).click()

        # 点击条目
        driver.find_element_by_xpath('//span[text()="企业会计准则要素表"]').click()

        # 输入编码规则
        # num2 = random.randint(999, 10000)
        driver.find_element_by_xpath(
            '//label[text()="科目编码规则"]/following-sibling::div//input'
        ).send_keys(34567)

        # 点击确定按钮
        driver.find_element_by_xpath(
            '//button[@class="primary mr20 btn btn-primary"]').click()
        sleep(2)
        # 断言
        self.assertIn(name, driver.page_source)

        # 点击应用按钮
        driver.find_element_by_xpath('//button[text()="引用"]').click()
        sleep(1)
        # 点击会计主体按钮
        driver.find_element_by_xpath(
            '//label[text()="会计主体"]/following-sibling::div//span[@class="input-group-addon cursor-style"]'
        ).click()

        # 点击条目
        driver.find_element_by_xpath('//span[text()="企业账号级"]').click()

        # 点击引用科目预制表右侧按钮
        driver.find_element_by_xpath(
            '//label[text()="引用预置科目表"]/following-sibling::div//span[@class="input-group-addon cursor-style"]'
        ).click()

        # 选择条目
        driver.find_element_by_xpath('//span[text()="基准科目表"]').click()

        # 输入编码
        num = random.randint(999, 10000)
        code = 'BM{}'.format(num)
        driver.find_element_by_xpath(
            '//label[text()="编码"]/following-sibling::div//input').send_keys(
                code)

        # 输入名称
        num1 = random.randint(999, 10000)
        name = '名称{}'.format(num1)
        driver.find_element_by_xpath(
            '//label[text()="名称"]/following-sibling::div//input').send_keys(
                name)

        # 输入编码规则
        # num2 = random.randint(999, 10000)
        # driver.find_element_by_xpath('//label[text()="科目编码规则"]/following-sibling::div//input').send_keys(34567)

        # 点击确定按钮
        driver.find_element_by_xpath(
            '//button[@class="primary mr20 btn btn-primary"]').click()
        sleep(2)
        # 断言
        self.assertIn(name, driver.page_source)

        # 点击打印按钮
        driver.find_element_by_xpath('//button[text()="打印"]').click()
        sleep(1)

        # 点击关闭按钮
        driver.find_element_by_xpath('//button[text()="关闭"]').click()

        driver.switch_to.default_content()

        driver.find_element_by_class_name('u-button').click()
        sleep(1)
        driver.find_element_by_class_name('u-dropdown-menu-item').click()
예제 #49
0
    def runTest(self):
        driver = self.getDriver()
        param = self.param
        tool = utils
        driver.refresh()
        # 左上方公共节点
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_class_name('lebra-navbar-left-icon')))
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()

        # 进入财务管理
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//*[text()="财务管理"]')))
        driver.find_element_by_xpath('//*[text()="财务管理"]').click()
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_css_selector('span[title="总账"]')))
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="总账"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_css_selector(
                    'li[class="bottomBar"][title="现金流量项目"]')))
        # 进入二级节点
        menu3 = driver.find_element_by_css_selector(
            'li[class="bottomBar"][title="现金流量项目"]')
        actions.move_to_element(menu3)
        actions.click(menu3)
        actions.perform()
        # 断言
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_css_selector(
                    '#home_header > div > div.tab--38iB- > ul > li > p')))
        titleName = driver.find_element_by_css_selector(
            '#home_header > div > div.tab--38iB- > ul > li > p').get_attribute(
                'title')
        assert u"现金流量项目" in titleName, u"页面源码中不存在该关键字!"
        locate = (By.ID, 'cashflowitem', 'Undefined')
        WebDriverWait(driver, 10,
                      0.5).until(ec.presence_of_element_located(locate))
        iframe = driver.find_element_by_id('cashflowitem')
        driver.switch_to.frame(iframe)

        # 点击会计主体右侧按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//span[text()="会计主体"]/parent::div/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
                )))
        driver.find_element_by_xpath(
            '//span[text()="会计主体"]/parent::div/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
        ).click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//div[text()="企业账号级"]')))
        driver.find_element_by_xpath('//div[text()="企业账号级"]').click()

        # 点击现金流量类型右侧按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//span[text()="现金流量类型"]/parent::div/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
                )))
        driver.find_element_by_xpath(
            '//span[text()="现金流量类型"]/parent::div/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]'
        ).click()
        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//div[@role="listbox"]/div[1]')))
        driver.find_element_by_xpath('//div[@role="listbox"]/div[1]').click()
        # 新增
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(driver.find_element_by_xpath('//*[text()="新增"]')))
        driver.find_element_by_xpath('//*[text()="新增"]').click()
        # 输入编码
        num = random.randint(999, 10000)
        code = '编码{}'.format(num)
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//label[text()="编码"]/following-sibling::div//input')))
        driver.find_element_by_xpath(
            '//label[text()="编码"]/following-sibling::div//input').send_keys(
                code)

        # 输入名称
        num1 = random.randint(999, 10000)
        name = '现金流量类型{}'.format(num1)
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//label[text()="名称"]/following-sibling::div//input')))
        driver.find_element_by_xpath(
            '//label[text()="名称"]/following-sibling::div//input').send_keys(
                name)

        # 点击确定按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//button[text()="确定"]')))
        driver.find_element_by_xpath('//button[text()="确定"]').click()

        # 断言
        self.assertIn(name, driver.page_source)

        # 点击编辑
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//span[text()="{}"]/ancestor::tr'.format(name))))

        # 鼠标移动
        ele = driver.find_element_by_xpath(
            '//span[text()="{}"]/ancestor::tr'.format(name))
        action = ActionChains(driver)
        action.move_to_element(ele)
        action.perform()
        driver.find_element_by_xpath(
            '//span[text()="{}"]/ancestor::tr//span[text()="编辑"]'.format(
                name)).click()

        # 点击确定按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//button[text()="确定"]')))
        driver.find_element_by_xpath('//button[text()="确定"]').click()

        # 点击删除
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//span[text()="{}"]/ancestor::tr'.format(name))))

        # 鼠标移动
        ele = driver.find_element_by_xpath(
            '//span[text()="{}"]/ancestor::tr'.format(name))
        action = ActionChains(driver)
        action.move_to_element(ele)
        action.perform()
        driver.find_element_by_xpath(
            '//span[text()="{}"]/ancestor::tr//span[text()="删除"]'.format(
                name)).click()

        # 点击确定按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//button[text()="确定"]')))
        driver.find_element_by_xpath('//button[text()="确定"]').click()

        self.assertNotIn(name, driver.page_source)

        driver.switch_to.default_content()
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(driver.find_element_by_class_name('u-button')))
        driver.find_element_by_class_name('u-button').click()
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_class_name('u-dropdown-menu-item')))
        driver.find_element_by_class_name('u-dropdown-menu-item').click()
def _test_Avartrees(browser):
    project_dict, workspace_page = startup(browser)

    # Import variable_editor.py
    file_path = pkg_resources.resource_filename('openmdao.gui.test.functional',
                                                'files/model_vartree.py')
    workspace_page.add_file(file_path)

    workspace_page.add_library_item_to_dataflow('model_vartree.Topp', "top")

    comp = workspace_page.get_dataflow_figure('p1', "top")
    editor = comp.editor_page()
    editor.move(-100, 0)
    inputs = editor.get_inputs()
    expected = [
        ['', ' cont_in', '', '', ''],
        [
            '', 'directory', '', '',
            'If non-blank, the directory to execute in.'
        ],
        [
            '', 'force_fd', 'False', '',
            'If True, always finite difference this component.'
        ],
        [
            '', 'missing_deriv_policy', 'error', '',
            'Determines behavior when some analytical derivatives are provided but some are missing'
        ]
    ]

    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    # Expand first vartree
    inputs.rows[0].cells[1].click()
    inputs = editor.get_inputs()
    expected = [
        ['', ' cont_in', '', '', ''], ['', 'v1', '1', '', 'vv1'],
        ['', 'v2', '2', '', 'vv2'], ['', ' vt2', '', '', ''],
        [
            '', 'directory', '', '',
            'If non-blank, the directory to execute in.'
        ],
        [
            '', 'force_fd', 'False', '',
            'If True, always finite difference this component.'
        ],
        [
            '', 'missing_deriv_policy', 'error', '',
            'Determines behavior when some analytical derivatives are provided but some are missing'
        ]
    ]

    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    # While expanded, verify that 'v1' is editable.
    inputs.rows[1].cells[2].click()
    inputs = editor.get_inputs()
    inputs[1][2] = "42"
    expected[1][2] = "42"

    time.sleep(0.5)
    inputs = editor.get_inputs()
    # FIXME sometimes row 2 gets a value of '' because slickgrid is editing it.
    #    for i, row in enumerate(inputs.value):
    #        eq(row, expected[i])
    eq(inputs.value[1], expected[1])

    # While expanded, verify that cell that became the 2nd vartree is now
    # uneditable
    inputs.rows[3].cells[1].click()
    inputs = editor.get_inputs()
    try:
        inputs[3][2] = "abcd"
    except IndexError:
        pass
    else:
        raise TestCase.failureException(
            'Exception expected: VarTree value should not be settable on inputs.'
        )

    # Contract first vartree
    inputs.rows[0].cells[1].click()
    inputs = editor.get_inputs()
    expected = [
        ['', ' cont_in', '', '', ''],
        [
            '', 'directory', '', '',
            'If non-blank, the directory to execute in.'
        ],
        [
            '', 'force_fd', 'False', '',
            'If True, always finite difference this component.'
        ],
        [
            '', 'missing_deriv_policy', 'error', '',
            'Determines behavior when some analytical derivatives are provided but some are missing'
        ]
    ]

    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    editor.close()

    # Now, do it all again on the Properties Pane
    workspace_page('properties_tab').click()
    obj = workspace_page.get_dataflow_figure('p1', 'top')
    chain = ActionChains(browser)
    chain.click(obj.root)
    chain.perform()
    inputs = workspace_page.props_inputs
    expected = [[' cont_in', ''], ['directory', ''], ['force_fd', 'False'],
                ['missing_deriv_policy', 'error']]

    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    # Expand first vartree
    inputs.rows[0].cells[0].click()
    inputs = workspace_page.props_inputs
    expected = [[' cont_in', ''], ['v1', '42'], ['v2', '2'], [' vt2', ''],
                ['directory', ''], ['force_fd', 'False'],
                ['missing_deriv_policy', 'error']]

    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    # While expanded, verify that 'v1' is editable.
    inputs.rows[1].cells[1].click()
    inputs = workspace_page.props_inputs
    inputs[1][1] = "43"
    expected[1][1] = "43"

    time.sleep(1)
    inputs = workspace_page.props_inputs
    # FIXME sometimes row 2 gets a value of '' because slickgrid is editing it.
    #    for i, row in enumerate(inputs.value):
    #        eq(row, expected[i])
    eq(inputs.value[1], expected[1])

    # Contract first vartree
    inputs.rows[0].cells[0].click()
    inputs = workspace_page.props_inputs
    expected = [[' cont_in', ''], ['directory', ''], ['force_fd', 'False'],
                ['missing_deriv_policy', 'error']]

    for i, row in enumerate(inputs.value):
        eq(row, expected[i])

    # Clean up.
    closeout(project_dict, workspace_page)
예제 #51
0
def info_scrapping(browser, list_people_url, current_company):
    ## Scrape each person's information from profile
    try:
        CACHE_FNAME = 'people_cache.json'
        cache_file = open(CACHE_FNAME, 'r')
        cache_content = cache_file.read()
        dic_data = json.loads(cache_content)
        cache_file.close()
        if current_company.name in dic_data:
            dic_this = dic_data[current_company.name]
        elif current_company.name.title() in dic_data:
            dic_this = dic_data[current_company.name.title()]
        else:
            dic_data[current_company.name] = {}
            dic_this = {}
    except:
        dic_data = {}
        dic_data[current_company.name] = {}
    cur_dic = dic_data[current_company.name]
    for i in range(len(list_people_url)):
        url_cur = list_people_url[i]
        if url_cur in dic_this:
            print('Already had it in cache...')
            c_p = dic_this[url_cur]
            person = Person(name=c_p['name'],
                            title=c_p['title'],
                            location=c_p['location'],
                            skills=c_p['skills'],
                            school=c_p['school_recent'])
            current_company.add_employee(person)
        else:
            browser.get(url_cur)
            try:
                WebDriverWait(browser, 10).until(
                    expected_conditions.presence_of_element_located(
                        (By.TAG_NAME, "h1")))
            finally:
                name = browser.find_element_by_tag_name('h1').text
                job_title = browser.find_element_by_tag_name('h2').text
                location = browser.find_element_by_tag_name('h3').text
                browser.execute_script(
                    "window.scrollTo(0, 0.5*document.body.scrollHeight);")
                time.sleep(2)
            try:
                WebDriverWait(browser, 10).until(
                    expected_conditions.presence_of_element_located(
                        (By.CLASS_NAME,
                         "pv-profile-section__card-action-bar")))
                showmore_button = browser.find_element_by_class_name(
                    'pv-profile-section__card-action-bar')
                actions = ActionChains(browser)
                actions.move_to_element(showmore_button).perform()
                time.sleep(2)
                actions.click(showmore_button).perform()
            except:
                print('No skill found')
            finally:
                # showmore_button.click()
                skills = browser.find_elements_by_class_name(
                    'pv-skill-category-entity__name')
            skills_list = []
            for skill in skills:
                skills_list.append(skill.text)
            try:
                school = browser.find_elements_by_class_name(
                    'pv-entity__school-name')[0].text
            except:
                school = ''
            cur_dic[url_cur] = {
                'name': name,
                'title': job_title,
                'location': location,
                'skills': skills_list,
                'school_recent': school
            }
            person = Person(name=name,
                            title=job_title,
                            location=location,
                            skills=skills_list,
                            school=school)
            current_company.add_employee(person)
    ## Save the data in json file
    cache_file = open(CACHE_FNAME, 'w')
    dic_data[current_company.name] = cur_dic
    cache_file.write(json.dumps(dic_data))
    cache_file.close()
    return current_company
예제 #52
0
 #--- City ---
 button2click = ids[idNum_city]; #get it
 button2click.click(); #click it
 actions = ActionChains(driver); #fire up the actions
 actions.send_keys(city).perform(); #write in the city
 
 #--- State ---
 button2click = ids[idNum_state]; #get it
 button2click.click(); #click it
 button2click.click(); #click it again
 actions = ActionChains(driver); #fire up the actions
 actions.send_keys(stater).perform(); #write in the stater
 buttonSize = button2click.size;
 actions = ActionChains(driver); #fire up the actions
 actions.move_to_element_with_offset(button2click, buttonSize['width']//2, 3*buttonSize['height']//2);
 actions.click();
 actions.perform();
 
 #--- Zip ---
 button2click = ids[idNum_zip]; #get it
 button2click.click(); #click it
 actions = ActionChains(driver); #fire up the actions
 actions.send_keys(zipper).perform(); #write in the city
 
 #--- Occupation ---
 button2click = ids[idNum_occ]; #get it
 button2click.click(); #click it
 button2click.click(); #click it again
 actions = ActionChains(driver); #fire up the actions
 actions.send_keys(occupation).perform(); #write in the occ
 buttonSize = button2click.size;
예제 #53
0
    def runTest(self):
        driver = self.getDriver()
        param = self.param
        tool = utils
        driver.refresh()
        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()
        sleep(1)
        # 进入财务管理
        driver.find_element_by_xpath('//*[text()="财务管理"]').click()
        sleep(1)
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="费用管理"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(1)
        # 进入二级节点
        menu3 = driver.find_element_by_css_selector(
            'li[class="bottomBar"][title="申请控制"]')
        actions.move_to_element(menu3)
        actions.click(menu3)
        actions.perform()

        sleep(1)
        titleName = driver.find_element_by_css_selector(
            '#home_header > div > div.tab--38iB- > ul > li > p').get_attribute(
                'title')
        assert u"申请控制" in titleName, u"页面源码中不存在该关键字!"
        sleep(1)
        iframe = driver.find_element_by_id('FICO_SQKZ')
        driver.switch_to.frame(iframe)

        # 新增
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(driver.find_element_by_xpath('//*[text()="新增"]')))
        driver.find_element_by_xpath('//*[text()="新增"]').click()

        driver.find_element_by_xpath('//*[text()="取消"]').click()
        button1 = driver.find_element_by_xpath('//*[text()="确 认"]')
        driver.execute_script("arguments[0].click();", button1)

        # 新增
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(driver.find_element_by_xpath('//*[text()="新增"]')))
        driver.find_element_by_xpath('//*[text()="新增"]').click()

        # 输入申请单
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//div[text()="申请单"]/following-sibling::div//input[1]')))
        driver.find_element_by_xpath(
            '//div[text()="申请单"]/following-sibling::div//input[1]').click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
                )))
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
        ).click()

        # 点击申请控制对象
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//div[text()="申请控制对象"]/following-sibling::div//input[1]'))
        )
        driver.find_element_by_xpath(
            '//div[text()="申请控制对象"]/following-sibling::div//input[1]').click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
                )))
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
        ).click()

        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//button[text()="保存"]')))
        # 点击保存
        driver.find_element_by_xpath('//button[text()="保存"]').click()

        # 断言
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]'
                )))
        ele = driver.find_element_by_xpath(
            '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]'
        )
        self.assertIsNotNone(ele)

        # 点击编辑按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]//a[text()="编辑"]'
                )))
        driver.find_element_by_xpath(
            '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]//a[text()="编辑"]'
        ).click()

        # 点击允许例外按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//div[text()="允许例外"]/span')))
        driver.find_element_by_xpath('//div[text()="允许例外"]/span').click()

        # 点击职务输入框
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//div[text()="职务"]/parent::div/div[2]//input')))
        driver.find_element_by_xpath(
            '//div[text()="职务"]/parent::div/div[2]//input').click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
                )))
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
        ).click()

        # 点击用户输入框
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//div[text()="用户"]/parent::div/div[2]//input')))

        # 移动滚动条
        element = driver.find_element_by_xpath(
            '//div[text()="用户"]/parent::div/div[2]//input')
        driver.execute_script('arguments[0].scrollIntoView();', element)

        driver.find_element_by_xpath(
            '//div[text()="用户"]/parent::div/div[2]//input').click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
                )))
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
        ).click()

        # 点击职级输入框
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//div[text()="职级"]/parent::div/div[2]//input')))
        driver.find_element_by_xpath(
            '//div[text()="职级"]/parent::div/div[2]//input').click()

        # 选择一个条目
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
                )))
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]'
        ).click()

        # 点击保存
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath('//button[text()="保存"]')))
        driver.find_element_by_xpath('//button[text()="保存"]').click()

        # 点击删除按钮
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]//a[text()="删除"]'
                )))
        driver.find_element_by_xpath(
            '//*[@id="root"]/div/div[2]/div/div[1]/div[2]/div/table/tbody/tr[1]//a[text()="删除"]'
        ).click()

        # 点击确定
        WebDriverWait(driver, 10, 0.5).until(
            ec.visibility_of(
                driver.find_element_by_xpath(
                    '//button[@class="ant-btn ant-btn-danger"]')))
        driver.find_element_by_xpath(
            '//button[@class="ant-btn ant-btn-danger"]').click()

        driver.switch_to.default_content()
        driver.find_element_by_class_name('u-button').click()
        sleep(1)
        driver.find_element_by_class_name('u-dropdown-menu-item').click()
예제 #54
0
from selenium.webdriver import ActionChains
from selenium import webdriver
import time
'''
1.鼠标悬停到设置
2.点击高级设置
'''
driver = webdriver.Chrome()
driver.implicitly_wait(20)
driver.maximize_window()
driver.get('https://www.baidu.com')
# 鼠标悬停到设置
# 第一步:初始化actionchains
action = ActionChains(driver)
# 第二步: 定位要操作的元素
ele = driver.find_element_by_xpath('//span[@name="tj_settingicon"]')
# 第三步:执行对应的操作,右击
action.move_to_element(ele).perform()
# 第四步:操作完以后要释放动作
# action.perform()
# time.sleep(2)

# 点击高级搜索
ele1 = driver.find_element_by_xpath('//a[text()="高级搜索"]')
action.click(ele1).perform()
# action.perform()
예제 #55
0
time.sleep(1)

# 연결하는 방식
# # 아이디 박스, 비밀번호 박스, 로그인 버튼 찾아놓기
# id_box = driver.find_element_by_css_selector('.login-container__login-input')
# pw_box = driver.find_element_by_css_selector('.login-container__password-input')
# login_button = driver.find_element_by_css_selector('.login-container__login-button')
#
# # 액션 실행
# (ActionChains(driver)
#     .send_keys_to_element(id_box, 'codeit')
#     .send_keys_to_element(pw_box, 'datascience')
#     .click(login_button)
#     .perform())

# 나열하는 방식
# 아이디 박스, 비밀번호 박스, 로그인 버튼 찾아놓기
id_box = driver.find_element_by_css_selector('.login-container__login-input')
pw_box = driver.find_element_by_css_selector('.login-container__password-input')
login_button = driver.find_element_by_css_selector('.login-container__login-button')

# 액션 실행
actions = ActionChains(driver)
actions.send_keys_to_element(id_box, 'codeit')
actions.send_keys_to_element(pw_box, 'datascience')
actions.click(login_button)
actions.perform()

driver.quit()

예제 #56
0
    def runTest(self):
        driver = self.getDriver()
        driver.implicitly_wait(30)
        param = self.param
        tool = utils
        driver.refresh()
        # driver.find_element_by_xpath('//*[@id="_dropdown_popcontainer"]/div/i').click()
        # driver.find_element_by_xpath('//*[@id="home_header"]//div[text()="UI测试专属"]').click()
        # driver.find_element_by_xpath(
        #     '//button[@class="u-button btn__style___37bsb u8c_primary__style___RFibc  btn__style___20DQM "]').click()
        # sleep(2)
        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()
        sleep(2)
        # 进入社交协同
        driver.find_element_by_xpath('//*[text()="人力资源"]').click()
        sleep(2)
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="假勤管理"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(2)
        # 进入二级节点
        driver.find_element_by_xpath('//li[@title="考勤统计规则"]').click()

        sleep(2)
        # 跳转考勤统计规则iframe
        iframe = driver.find_element_by_id('HRJQ020050')
        # # driver.switch_to.frame(iframe)
        SwitchTo(driver).frame(iframe)
        sleep(2)

        # 点击添加按钮
        driver.find_element_by_xpath('//*[@id="item"]/div[1]/div[1]/div/div[1]/ul/li[1]').click()
        sleep(1)

        # 输入考勤规则
        num = random.randint(10000, 99999)
        str_regular = "统计规则{}".format(num)
        driver.find_element_by_xpath('//label[text()="考勤统计规则名称"]/following-sibling::div//input').send_keys(str_regular)
        # 点击组织右侧按钮
        driver.find_element_by_xpath('//*[@id="c60"]/div/span/span/span/i[2]').click()
        sleep(3)

        # 选中组织
        driver.find_element_by_xpath(
            '//div[@role="dialog"]//span[text()="仓储中心-北京"]').click()

        # 点击确认
        driver.find_element_by_xpath(
            '//div[@class="el-dialog__wrapper custom-ref-dialog"]//button[@class="el-button el-button--primary"]').click()

        # 点击保存
        driver.find_element_by_xpath('//div[@aria-label="新增考勤统计规则方案"]//button[@class="el-button el-button--primary"]').click()


        sleep(3)
        # 断言
        text = driver.find_element_by_xpath(
            '//span[text()="{}"]'.format(str_regular)).text
        self.assertEqual(text, str_regular)

        # 编辑考勤规则
        driver.find_element_by_xpath(
            '//*[@id="item"]/div[1]/div[1]/div/div[1]/ul/li[3]').click()
        sleep(3)

        # 输入考勤规则
        num = random.randint(10000, 99999)
        str_regular_edit = "统计规则{}".format(num)
        driver.find_element_by_xpath('//label[text()="考勤统计规则名称"]/following-sibling::div//input').clear()
        driver.find_element_by_xpath('//label[text()="考勤统计规则名称"]/following-sibling::div//input').send_keys(str_regular_edit)
        # 点击保存按钮
        driver.find_element_by_xpath('//div[@aria-label="编辑考勤统计规则方案"]//button[@class="el-button el-button--primary"]').click()
        sleep(2)
        # 断言
        text = driver.find_element_by_xpath(
            '//span[text()="{}"]'.format(str_regular_edit)).text
        self.assertEqual(text, str_regular_edit)

        # 点击新建项目
        driver.find_element_by_xpath('//button[@class="el-button el-button--primary"]/span[text()="新增项目"]').click()
        # 新增自定义项目
        driver.find_element_by_xpath('//button[@class="el-button select-button el-button--text"]/span[text()="新增自定义项目"]').click()

        # 输入项目名称信息
        driver.find_element_by_xpath('//label[text()="项目名称:"]/following-sibling::div//input').send_keys("项目12345")

        # 输入说明信息
        driver.find_element_by_xpath('//div[@class="el-form-item__content"]//textarea').send_keys("说明信息87654")

        # 点击保存
        driver.find_element_by_xpath('//button/span[text()="保存"]').click()
        sleep(10)
        ele = driver.find_element_by_xpath('//span[text()="项目12345"]')
        self.assertIsNotNone(ele)

        # 点击编辑按钮
        driver.find_element_by_xpath('//span[text()="项目12345"]/ancestor::tr/td[6]//div[text()="编辑"]').click()
        sleep(1)

        # 点击保存
        driver.find_element_by_xpath('//button/span[text()="保存"]').click()
        sleep(10)
        # 点击删除按钮
        driver.find_element_by_xpath('//span[text()="项目12345"]/ancestor::tr/td[6]//div[text()="删除"]').click()
        sleep(1)

        # 点击取消按钮
        driver.find_element_by_xpath('//div[@class="el-message-box"]//button[1]').click()
        sleep(0.5)
        self.assertEqual("已取消删除",driver.find_element_by_xpath('//p[text()="已取消删除"]').text)

        # 点击删除按钮
        driver.find_element_by_xpath('//span[text()="项目12345"]/ancestor::tr/td[6]//div[text()="删除"]').click()
        sleep(1)

        # 点击确定按钮
        driver.find_element_by_xpath('//div[@class="el-message-box"]//button[2]').click()
        sleep(0.5)
        self.assertEqual("操作成功!",driver.find_element_by_xpath('//p[text()="操作成功!"]').text)


        # 点击删除按钮
        driver.find_element_by_xpath('//*[@id="item"]/div[1]/div[1]/div/div[1]/ul/li[2]').click()
        sleep(0.5)
        driver.find_element_by_xpath('//div[@class="el-message-box"]//button[2]').click()
        sleep(0.5)
        # 断言
        self.assertEqual("操作成功", driver.find_element_by_xpath('//p[text()="操作成功"]').text)

        # 关闭当前页面
        driver.switch_to.default_content()
        sleep(1)
        driver.find_element_by_xpath('//*[@id="home_header"]/div/div[3]/ul/li/div').click()
예제 #57
0
    def runTest(self):
        driver = self.getDriver()
        param = self.param
        tool = utils
        driver.refresh()
        # 左上方公共节点
        driver.find_element_by_class_name('lebra-navbar-left-icon').click()
        sleep(1)
        # 进入财务管理
        driver.find_element_by_xpath('//*[text()="财务管理"]').click()
        sleep(1)
        # 进入一级节点
        menu2 = driver.find_element_by_css_selector('span[title="财务公共"]')
        actions = ActionChains(driver)
        actions.move_to_element(menu2)
        actions.click(menu2)
        actions.perform()
        sleep(1)
        # 进入二级节点
        menu3 = driver.find_element_by_css_selector('li[class="bottomBar"][title="会计科目"]')
        actions.move_to_element(menu3)
        actions.click(menu3)
        actions.perform()

        sleep(2)
        titleName = driver.find_element_by_css_selector(
            '#home_header > div > div.tab--38iB- > ul > li > p').get_attribute('title')
        assert u"会计科目" in titleName, u"页面源码中不存在该关键字!"
        sleep(2)
        iframe = driver.find_element_by_id('setting_accsubject')
        driver.switch_to.frame(iframe)
        sleep(1)

        # 点击会计主体
        driver.find_element_by_xpath(
            '//span[text()="会计主体"]/parent::div/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]').click()

        # 选择条目
        driver.find_element_by_xpath('//div[text()="企业账号级"]').click()

        # 点击科目表右侧按钮
        driver.find_element_by_xpath(
            '//span[text()="科目表"]/parent::div/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]').click()

        # 选择条目第一条
        driver.find_element_by_xpath('//div[@role="listbox"]/div[1]').click()
        sleep(2)
        #

        # 点击科目新增
        driver.find_element_by_xpath('//button[@class="btn btn-primary mr10 iconfont noprint"]').click()
        sleep(1)

        # 输入科目编码
        num = random.randint(1000, 9999)
        driver.find_element_by_xpath('//label[text()="科目编码"]/following-sibling::div/input').send_keys(num)

        # 输入名称
        num1 = random.randint(999, 10000)
        name = '名称{}'.format(num1)
        driver.find_element_by_xpath('//label[text()="科目名称"]/following-sibling::div//input').send_keys(name)

        # 点击会计要素表右侧按钮
        driver.find_element_by_xpath(
            '//label[text()="会计要素"]/following-sibling::div//span[@class="input-group-addon cursor-style"]').click()

        # 点击条目
        driver.find_element_by_xpath('//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]').click()

        # 点击确定按钮
        driver.find_element_by_xpath('//button[text()="确定"]').click()
        sleep(1)
        # 断言
        self.assertIn(name, driver.page_source)

        # 鼠标移动
        # 点击编辑按钮
        ele = driver.find_element_by_xpath('//span[text()="{}"]/ancestor::tr//input'.format(name))
        action = ActionChains(driver)
        action.move_to_element(ele)
        action.perform()
        driver.find_element_by_xpath('//span[text()="{}"]/ancestor::tr//input'.format(name)).click()

        # 点击编辑按钮
        driver.find_element_by_xpath('//span[text()="{}"]/ancestor::tr//span[text()="编辑"]'.format(name)).click()
        sleep(1)
        # 点击确定按钮
        driver.find_element_by_xpath('//button[text()="确定"]').click()
        # 鼠标移动
        # 点击编辑按钮
        ele = driver.find_element_by_xpath('//span[text()="{}"]/ancestor::tr//input'.format(name))
        action = ActionChains(driver)
        action.move_to_element(ele)
        action.perform()
        driver.find_element_by_xpath('//span[text()="{}"]/ancestor::tr//input'.format(name)).click()

        # 点击删除按钮
        driver.find_element_by_xpath('//span[text()="{}"]/ancestor::tr//span[text()="删除"]'.format(name)).click()
        sleep(1)
        # 点击确定
        driver.find_element_by_xpath('//button[text()="确定"]').click()

        # 新建一条数据*****************************************************************************
        # 点击科目表右侧按钮
        driver.find_element_by_xpath(
            '//span[text()="科目表"]/parent::div/following-sibling::div[1]//span[@class="Select-arrow-zone iconfont icon-chevron-down"]').click()

        # 选择条目第一条
        driver.find_element_by_xpath('//div[@role="listbox"]/div[1]').click()
        sleep(2)
        #

        # 点击科目新增
        driver.find_element_by_xpath('//button[@class="btn btn-primary mr10 iconfont noprint"]').click()
        sleep(1)

        # 输入科目编码
        num = random.randint(1000, 9999)
        driver.find_element_by_xpath('//label[text()="科目编码"]/following-sibling::div/input').send_keys(num)

        # 输入名称
        num1 = random.randint(999, 10000)
        name = '名称{}'.format(num1)
        driver.find_element_by_xpath('//label[text()="科目名称"]/following-sibling::div//input').send_keys(name)

        # 点击会计要素表右侧按钮
        driver.find_element_by_xpath(
            '//label[text()="会计要素"]/following-sibling::div//span[@class="input-group-addon cursor-style"]').click()

        # 点击条目
        driver.find_element_by_xpath(
            '//ul[@class="dropdown-menu bootstrap-typeahead-menu dropdown-menu-justify"]/li[1]').click()

        # 点击确定按钮
        driver.find_element_by_xpath('//button[text()="确定"]').click()
        sleep(1)
        # 断言
        self.assertIn(name, driver.page_source)
        sleep(1)
        # 点击打印按钮
        driver.find_element_by_xpath('//button[text()="打印"]').click()
        sleep(1)

        # 点击关闭按钮
        driver.find_element_by_xpath('//button[text()="关闭"]').click()
        driver.switch_to.default_content()

        driver.find_element_by_class_name('u-button').click()
        sleep(1)
        driver.find_element_by_class_name('u-dropdown-menu-item').click()
예제 #58
0
class QuickView(Page):

    QUICK_VIEW_CONTAINER = (By.CSS_SELECTOR, "div.product-quick-view-container")
    QUICK_VIEW_BUTTONS = (By.CSS_SELECTOR, 'a.quick-view')
    IMAGE_SLIDER = (By.CSS_SELECTOR, 'div.product-gallery-slider button.next')
    DOTS = (By.CSS_SELECTOR, 'div.product-gallery-slider li')
    X_BUTTON = (By.CSS_SELECTOR, "button.mfp-close")
    QUICK_VIEW_ITEM_NAME = (By.CSS_SELECTOR, 'a.plain h1')
    QUICK_VIEW_ADD_TO_CART_BUTTON = (By.CSS_SELECTOR, "button.single_add_to_cart_button")
    QUICK_VIEW_PRODUCT_NAME = (By.CSS_SELECTOR, 'td.product-name')
    QUICK_VIEW_PRODUCT_IMAGE = (By.CSS_SELECTOR, 'div.slide.is-selected img')

    # User can open Quick View by clicking Quick View pop up and close by clicking X
    def open_and_closing_window(self):
        self.actions = ActionChains(self.driver)

        self.wait_for_presence_off_all_elements(self.QUICK_VIEW_BUTTONS)
        qv_buttons = self.find_elements(*self.QUICK_VIEW_BUTTONS)

        for product in range(len(qv_buttons)):

            self.actions = ActionChains(self.driver)
            # find again after reloading page
            button = self.find_elements(*self.QUICK_VIEW_BUTTONS)[product]
            # click QV button to open QV window
            self.actions.move_to_element(button).click().perform()
            #sleep(1)
            # click X button to close QV window
            self.wait_for_element(self.X_BUTTON)
            self.click(*self.X_BUTTON)
            self.wait_for_element_disappear(self.QUICK_VIEW_CONTAINER)

    # User can click Quick View, add product to cart, verify adding
    # exact item on cart counter and Cart Page
    def add_product_to_cart(self):

        self.wait_for_presence_off_all_elements(self.QUICK_VIEW_BUTTONS)
        qv_buttons = self.find_elements(*self.QUICK_VIEW_BUTTONS)

        for product in range(len(qv_buttons)):
            self.actions = ActionChains(self.driver)
            # find again after reloading page
            button = self.find_elements(*self.QUICK_VIEW_BUTTONS)[product]
            # click Quick View button to open Quick View window
            self.actions.move_to_element(button)
            self.actions.click().perform()
            self.wait_for_element(self.QUICK_VIEW_ITEM_NAME)

            # remember item name
            product_name = self.find_element(*self.QUICK_VIEW_ITEM_NAME).get_attribute('textContent')

            # click add to cart button
            self.wait_for_element(self.QUICK_VIEW_ADD_TO_CART_BUTTON)
            self.click(*self.QUICK_VIEW_ADD_TO_CART_BUTTON)

            # verify shopping cart counter changes to 1
            banner = TopMenu(self.driver)
            banner.verify_cart_counter('1')

            # click shopping cart button and go to cart page
            banner.click_cart_button()

            # verify quantity of items in the cart
            shopping_cart = ShoppingCart(self.driver)
            shopping_cart.verify_quantity_in_the_cart('1')

            # verify user added product with correct name
            shopping_cart.verify_added_product_name(product_name)

            # empty shopping cart
            shopping_cart.remove_item_from_card()

            # return to home page
            self.open_page()

    # User can open Quick View and click through product images
    def click_through_images(self):

        self.wait_for_presence_off_all_elements(self.QUICK_VIEW_BUTTONS)
        qv_buttons = self.find_elements(*self.QUICK_VIEW_BUTTONS)

        for product in range(len(qv_buttons)):
            # find again after reloading page
            self.actions = ActionChains(self.driver)
            # click Quick View pop up button
            button = self.find_elements(*self.QUICK_VIEW_BUTTONS)[product]
            self.actions.move_to_element(button).click().perform()

            # click through product images
            self.wait_for_presence_off_all_elements(self.DOTS)
            dots = self.find_elements(*self.DOTS)

            for _ in range(len(dots)):
                self.actions = ActionChains(self.driver)

                self.wait_for_presence_off_all_elements(self.DOTS)
                self.actions.click(dots[_]).perform()
                # verify image exists
                self.verify_image_present(*self.QUICK_VIEW_PRODUCT_IMAGE)

            # return to home page
            self.open_page()
예제 #59
0
class Login():
    def __init__(self):
        self.email='*****@*****.**'
        self.password='******'
        self.browser = webdriver.Chrome()
        self.browser.maximize_window()
        self.wait=WebDriverWait(self.browser,10)
        self.browser.get('https://auth.geetest.com/login/')
        self.action=ActionChains(self.browser)

    def user(self):
        email=self.browser.find_element(By.XPATH,'//*[@id="base"]/div[2]/div/div/div[3]/div/form/div[1]/div/div[1]/input')
        password=self.browser.find_element(By.XPATH,'//*[@id="base"]/div[2]/div/div/div[3]/div/form/div[2]/div/div[1]/input')
        self.action.click(email).perform()
        time.sleep(1)
        email.send_keys(self.email)
        time.sleep(1)
        self.action.click(password).perform()
        time.sleep(1)
        password.send_keys(self.password)
    def position(self):
        image=self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
        location=image.location
        location['x']=location['x']
        location['y']=location['y']
        size=image.size
        size['height']=size['height']
        size['width']=size['width']
        rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']),
          int(location['y'] + size['height']))
        return rangle

    def get_position1(self):
        #获取图片位置
        button1=self.browser.find_element(By.CLASS_NAME,'geetest_radar_tip')
        self.action.click(button1).perform()
        #self.browser.switch_to.frame(self.browser.find_element_by_tag_name("iframe"))
        #image1=self.browser.find_element(By.XPATH,'/html/body/div[3]/div[2]/div[1]/div/div[1]/div[1]/div/a/div[1]/canvas')
        rangle=self.position()
        return rangle

    def get_position2(self):
        button2=self.browser.find_element(By.CLASS_NAME,'geetest_slider_button')
        button2.click()
        rangle=self.position()
        return rangle

    def image(self,rangle):
        screenshot=self.browser.get_screenshot_as_png()
        screenshot=Image.open(BytesIO(screenshot))
        captche=screenshot.crop(rangle)
        return captche

    def get_image1(self):
        rangle=self.get_position1()
        time.sleep(2)
        captche=self.image(rangle)
        width=captche.size[0]
        height=captche.size[1]
        #captche = captche.resize((int(width*0.8), int(height*0.8)),Image.ANTIALIAS)
        captche.save('a.png')
        return captche

    def get_image2(self):
        rangle=self.get_position2()
        time.sleep(3)
        captche=self.image(rangle)
        width=captche.size[0]
        height=captche.size[1]
        #captche = captche.resize((int(width*0.8), int(height*0.8)),Image.ANTIALIAS)
        captche.save('b.png')
        return captche

    def is_pixel_equal(self, image1, image2, x, y):
        #判断两个像素是否相同
        pixel1=image1.load()[x,y]
        pixel2=image2.load()[x,y]
        a=pixel1[0]-pixel2[0]
        b=pixel1[1]-pixel2[2]
        c=pixel1[2]-pixel2[2]
        threshold=60
        if abs(a)<threshold and abs(b)<threshold and abs(c)<threshold:
            return True
        else:
            return False

    def get_gap(self, image1, image2):
        #获得缺口
        left=60    #滑片宽度
        for i in range(left, image1.size[0]):
            for j in range(image1.size[1]):
                if not self.is_pixel_equal(image1, image2, i, j):
                    left = i
                    return left
        return left

    def get_track(self,distance):
        #获得滑块的运动轨迹
        track=[]
        current=0
        v=0
        t=0.2
        m=distance*0.35
        n=distance*0.7
        while current<distance:
            if current<n:
                a=4
            else:
                a=-6
            v0=v
            v=v0+a*t
            move=v0*t+0.5*a*t*t
            current+=move
            track.append(round(move))
        return track

    def move_to_grap(self):
        image1=self.get_image1()
        image2=self.get_image2()
        success=self.browser.find_element(By.CLASS_NAME,'geetest_success_radar_tip_content')
        slider=self.browser.find_element(By.CLASS_NAME,'geetest_slider_button')
        button=self.browser.find_element(By.CLASS_NAME,'ivu-btn')
        # +20多向前移动20的距离
        distance=(self.get_gap(image1,image2)-6)+20
        print(distance)
        track=self.get_track(distance)
        print(track)
        back_tracks=[-3,-3,-2,-2,-2,-2,-2,-1,-1,-1,-1]     #待会回移的轨迹段
        # while success.text!='验证成功':
        # for i in range(0,2):
        self.action.click_and_hold(slider)
        for x in track:
           self.action.move_by_offset(xoffset=x,yoffset=0)
        time.sleep(0.5)
        for y in back_tracks:
            self.action.move_by_offset(xoffset=y,yoffset=0)
        self.action.move_by_offset(xoffset=-3,yoffset=0)         #小范围震荡
        self.action.move_by_offset(xoffset=3,yoffset=0)
        time.sleep(0.5)
        self.action.release(slider)
        self.action.perform()
        time.sleep(2)
        # print(success.text)
        # if success.text=='验证成功':
        self.action.click(button).perform()
예제 #60
0
options = ChromeOptions()
options.add_argument('start-maximized')
options.add_argument('test-type')
options.add_argument('enable-strict-powerful-feature-restrictions')
options.add_argument('disable-geolocation')
browser = webdriver.Chrome(options=options)
browser.get("https://www.gympass.com/")

try:
    action = ActionChains(browser)
    WebDriverWait(browser, 5).until(
        EC.visibility_of_element_located((By.LINK_TEXT, 'Entrar')))
    action.move_to_element(
        browser.find_element_by_link_text('Entrar')).perform()
    action.click().perform()

    WebDriverWait(browser, 5).until(
        EC.visibility_of_element_located((By.ID, 'username')))
    elem = browser.find_element_by_id('username')
    elem.send_keys(USERNAME, Keys.ENTER)
    time.sleep(2)

    WebDriverWait(browser, 5).until(
        EC.visibility_of_element_located((By.ID, 'password')))
    elem = browser.find_element_by_id('password')
    elem.send_keys(PASSWORD, Keys.ENTER)

    print('passo 0')
    browser.get('https://www.gympass.com/checkin')