def bing_search(start, end): # Generator: yield the url for beautifulsoup global number_of_urls_to_search local_count = number_of_urls_to_search driver = webdriver.PhantomJS(executable_path='D:/phantomjs-2.1.1-windows/bin/phantomJS') driver.get("http://global.bing.com/?FORM=HPCNEN&setmkt=en-us&setlang=en-us") try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "sb_feedback"))) except: raise finally: searchField = driver.find_element(By.ID, "sb_form_q") submitButton = driver.find_element(By.ID, "sb_form_go") actions = ActionChains(driver).click(searchField).send_keys(start + " " + end + " " + "text").click(submitButton) actions.perform() try: element = WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.CLASS_NAME, "b_footerRight"))) except: raise finally: bsObj = BeautifulSoup(driver.page_source, 'html.parser') results = bsObj.findAll('li', {'class': 'b_algo'}) for result in results: if not local_count: driver.close() return print(result.a['href']) yield result.a['href'] local_count -= 1 driver.close()
def add_library_item_to_dataflow(self, item_name, instance_name, check=True, offset=None, prefix=None): """ Add component `item_name`, with name `instance_name`. """ library_item = self.get_library_item(item_name) target = WebDriverWait(self.browser, TMO).until( lambda browser: browser.find_element_by_xpath("//*[@id='-dataflow']") ) offset = offset or (90, 90) chain = ActionChains(self.browser) if False: chain.drag_and_drop(library_item, target) else: chain.click_and_hold(library_item) chain.move_to_element_with_offset(target, offset[0], offset[1]) chain.release(None) chain.perform() page = ValuePrompt(self.browser, self.port) page.set_value(instance_name) # Check that the prompt is gone so we can distinguish a prompt problem # from a dataflow update problem. time.sleep(0.25) self.browser.implicitly_wait(1) # We don't expect to find anything. try: eq(len(self.browser.find_elements(*page("prompt")._locator)), 0) finally: self.browser.implicitly_wait(TMO) retval = None if check: # Check that it's been added. retval = WebDriverWait(self.browser, TMO).until( lambda browser: self.get_dataflow_figure(instance_name, prefix) ) return retval
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 add_object_to_workflow_figure(self, obj_path, target_name, target_page=None): """ Add `obj_path` object to `target_name` in workflow diagram. """ if target_page is None: target_page = self for retry in range(3): try: items = obj_path.split('.') parent = items[:-1] comp = items[-1] obj = self.get_dataflow_figure(comp, parent) workflow = target_page.get_workflow_figure(target_name) flow_fig = workflow.flow chain = ActionChains(self.browser) chain.drag_and_drop(obj.root, flow_fig) chain.perform() except StaleElementReferenceException: if retry < 2: logging.warning('add_object_to_workflow_figure:' ' StaleElementReferenceException') else: raise else: break
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')
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"
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 _select_case(self, suite, case): """Select the test case. """ # select the case elem = Select(self._browser.find_element_by_id('select-dut')) elem.select_by_value(str(suite)) time.sleep(1) checkbox = None elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title') for elem in elems: action_chains = ActionChains(self._browser) action_chains.move_to_element(elem) action_chains.perform() logger.debug(elem.text) if elem.text.startswith(case): parent = elem.find_element_by_xpath('..') checkbox = parent.find_element_by_class_name('tree-checkbox') break if not checkbox: time.sleep(5) raise Exception('Failed to find the case') checkbox.click() time.sleep(1) elem = self._browser.find_element_by_id('runTest') elem.click() if not self.wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10): raise Exception('Failed to start test case')
def find_soup(domain_name, driver, form_name): # element_to_be_clickable, presence_of_element_located WebDriverWait(driver, MAX_WAIT).until(EC.element_to_be_clickable((By.ID, form_name))) domain_form = driver.find_element_by_id(form_name) WebDriverWait(driver, MAX_WAIT).until(EC.element_to_be_clickable((By.ID, form_name))) domain_form.clear() type_new = ActionChains(driver).click(domain_form).send_keys(domain_name) type_new.perform() driver.implicitly_wait(0.1) wait_attempts = 0 while domain_form.get_attribute('value') != domain_name: driver.implicitly_wait(5) wait_attempts += 1 if wait_attempts > WAIT_ATTEMPTS: break submit_new = ActionChains(driver).click(domain_form).send_keys(Keys.ENTER) submit_new.perform() WebDriverWait(driver, MAX_WAIT).until(EC.element_to_be_clickable((By.ID, "domain_search_input"))) source = driver.page_source soup = BeautifulSoup(source, "html.parser") godaddy_link = 'https://www.godaddy.com/domains/searchresults.aspx?checkAvail=1&domainToCheck=' + domain_name # Can't do the following b/c the browser url doesn't change when editing form within page: godaddy_link = driver.current_url return soup, godaddy_link, driver
def test_student_find_the_cc_book_from_an_online_search_7742(self): """Find the Concept Coach book from an online search. Steps: Search the title of the book, with 'openstax' through a search engine Expected Result: The search returns a link to the book """ self.ps.test_updates['name'] = 'cc1.12.003' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['cc1', 'cc1.12', 'cc1.12.003', '7742'] self.ps.test_updates['passed'] = False # Test steps and verification assertions self.student.driver.get('https://www.google.com') self.student.page.wait_for_page_load() actions = ActionChains(self.student.driver) actions.send_keys('openstax concept coach biology') actions.send_keys(Keys.RETURN) actions.perform() self.student.wait.until( expect.visibility_of_element_located( (By.XPATH, '//a[contains(text(),"Biology with Concept Coach")]') ) ) self.student.driver.find_element( By.XPATH, '//cite[contains(text(),"https://cnx.org/")]') self.ps.test_updates['passed'] = True
def _select_case(self, role, case): """Select the test case. """ # select the case elem = Select(self._browser.find_element_by_id('select-dut')) elem.select_by_value(str(role)) time.sleep(1) checkbox = None wait_until(lambda: self._browser.find_elements_by_css_selector('.tree-node .tree-title') and True) elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title') finder = re.compile(r'.*\b' + case + r'\b') finder_dotted = re.compile(r'.*\b' + case.replace(' ', r'\.') + r'\b') for elem in elems: action_chains = ActionChains(self._browser) action_chains.move_to_element(elem) action_chains.perform() logger.debug(elem.text) if finder.match(elem.text) or finder_dotted.match(elem.text): parent = elem.find_element_by_xpath('..') checkbox = parent.find_element_by_class_name('tree-checkbox') break if not checkbox: time.sleep(5) raise Exception('Failed to find the case') self._browser.execute_script("$('.overview').css('left', '0')") checkbox.click() time.sleep(1) elem = self._browser.find_element_by_id('runTest') elem.click() if not wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10): raise Exception('Failed to start test case')
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()
def test_event_detail_page_tab2(self): """ Test that the adverse event page has the tab and accordion items we expect :return: """ # I want to see the top drugs that have a given adverse event # I want to see the sex and age breakdown of the top drugs that have a given adverse event item = CATEGORIES[1] self.driver.get('%s/search/events/?q=%s' % (self.live_server_url, item['search'], )) self.assertIn(item['detail'], self.driver.find_element_by_tag_name('h1').text) self.assertIn(item['search'], self.driver.find_element_by_tag_name('h1').text) # we should have two tabs self.assertEqual(2, len(self.driver.find_element_by_class_name('ui-tabs-nav').find_elements_by_tag_name('li'))) # I want to see drugs with this adverse event, so i click that tab self.driver.find_element_by_id('ui-id-2').click() # I see a chart with drug information and I click and mouse over the first bar to get the count chart_bar = self.driver.find_element_by_xpath( "//div[@id='adverseChart']//*[local-name()='svg']//*[local-name()='g'][@class='highcharts-series highcharts-tracker']/*[local-name()='rect']") chart_bar.click() hover = ActionChains(self.driver).move_to_element(chart_bar) hover.perform() tool_tip = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.XPATH, "//div[@class='highcharts-tooltip']/span/div/span"))) self.assertEqual('Count', tool_tip.text)
def go_to_my_room(self): self.wait_element_click(self.AVATAR) room = self.driver.find_element_by_xpath(self.AVATAR) mv = ActionChains(self.driver).move_to_element(room) mv.perform() room.click() return MyRoomPage(self.driver)
def add_object_to_workflow(self, obj_path, target_name): """ Add `obj_path` object to `target_name` in workflow. """ for retry in range(3): try: items = obj_path.split('.') parent = items[:-1] comp = items[-1] obj = self.get_dataflow_figure(comp, parent) target = self.find_object_button(target_name) chain = ActionChains(self.browser) chain.drag_and_drop(obj.root, target) chain.perform() #obj = self.find_object_button(obj_path) #workflow = self.get_workflow_figure(target_name) #flow_fig = workflow.flow #chain = ActionChains(self.browser) #chain.move_to_element(obj) #chain.click_and_hold(obj) #chain.move_to_element(flow_fig) #chain.move_by_offset(2, 1) #chain.release(None) #chain.perform() except StaleElementReferenceException: if retry < 2: logging.warning('add_object_to_workflow:' ' StaleElementReferenceException') else: raise else: break
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)
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 flip(self): """ Flip the workflow from horizontal to vertical or vice versa. """ chain = ActionChains(self.browser) chain.move_to_element_with_offset(self.flow, 5, 5) chain.context_click(None) chain.perform() time.sleep(0.5) self('flip_button').click()
def clear(self): """ Clear the workflow. """ chain = ActionChains(self.browser) chain.move_to_element_with_offset(self.flow, 5, 5) chain.context_click(None) chain.perform() time.sleep(0.5) self('clear_button').click()
def show_connected_variables(self): """ Show only the connected variables. """ chain = ActionChains(self.browser) chain.move_to_element_with_offset(self.connections_pane, 5, 5) chain.context_click(None) chain.perform() time.sleep(0.5) self('show_connected_button').click()
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)
def zoom_selection(self): center = self.driver.execute_script(GetScripts.getContainerCenter) actions = ActionChains(self.driver) actions.move_to_element_with_offset(self.element, int(center['x']), int(center['y'])) actions.key_down(Keys.SHIFT) actions.click_and_hold() actions.move_by_offset(300, 300) actions.release() actions.perform()
def run(self): """ Run this component. """ rect = self.root.find_element_by_css_selector('rect') chain = ActionChains(self.browser) chain.move_to_element_with_offset(rect, 15, 15) chain.context_click(None) chain.perform() time.sleep(0.5) self('run_button').click()
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()
def evaluate(self): """ Evaluate this component. (only available for ImplicitComponent) """ rect = self.root.find_element_by_css_selector('rect') chain = ActionChains(self.browser) chain.move_to_element_with_offset(rect, 15, 15) chain.context_click(None) chain.perform() time.sleep(0.5) self('evaluate_button').click()
def hover_by_id(self, element_id): """ Goes to the element by id and hovers. """ print "Executing hover over element by id = {0}".format(element_id) element = self.driver.find_element_by_id(element_id) hover = ActionChains(self.driver).move_to_element(element) hover.perform()
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)
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)
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()
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()
def test_asesoria_N_UX_link(driver): expectedurl = "http://gbh.com.do/servicio/desarrollo/asesoria-de-interfaz-y-experiencia-de-usuario-ui-ux/" try: dropdown = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "//li[@id='menu-item-209']"))) hover = ActionChains(driver).move_to_element(dropdown) hover.perform() element = driver.find_element(By.XPATH, "//li[@id='menu-item-2642']") element.click() driver.implicitly_wait(2) linkurl = driver.current_url except: linkurl = "" finally: driver.close() assert expectedurl == linkurl
def test_manejo_social_media_link(driver): expectedurl = "http://gbh.com.do/servicio/desarrollo/manejo-de-redes-sociales-para-empresas/" try: dropdown = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "//li[@id='menu-item-209']"))) hover = ActionChains(driver).move_to_element(dropdown) hover.perform() element = driver.find_element(By.XPATH, "//li[@id='menu-item-2895']") element.click() driver.implicitly_wait(2) linkurl = driver.current_url except: linkurl = "" finally: driver.close() assert expectedurl == linkurl
def test_mantenimiento_preventivo_correctivo_links(driver): expectedurl = "http://gbh.com.do/servicio/soporte/soporte-tecnico-mantenimiento-y-prevencion/" try: dropdown = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "//li[@id='menu-item-209']"))) hover = ActionChains(driver).move_to_element(dropdown) hover.perform() element = driver.find_element(By.XPATH, "//li[@id='menu-item-361']") element.click() driver.implicitly_wait(2) linkurl = driver.current_url except: linkurl = "" finally: driver.close() assert expectedurl == linkurl
def test_eval_infraestructura_IT_links(driver): expectedurl = "http://gbh.com.do/servicio/soporte/evaluacion-de-infraestructura-de-tecnologia-de-la-informacion/" try: dropdown = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "//li[@id='menu-item-209']"))) hover = ActionChains(driver).move_to_element(dropdown) hover.perform() element = driver.find_element(By.XPATH, "//li[@id='menu-item-392']") element.click() driver.implicitly_wait(2) linkurl = driver.current_url except: linkurl = "" finally: driver.close() assert expectedurl == linkurl
def test_install_redes_wifi(driver): expectedurl = "http://gbh.com.do/servicio/soporte/instalacion-y-configuracion-de-redes-wi-fi/" try: dropdown = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "//li[@id='menu-item-209']"))) hover = ActionChains(driver).move_to_element(dropdown) hover.perform() element = driver.find_element(By.XPATH, "//li[@id='menu-item-358']") element.click() driver.implicitly_wait(2) linkurl = driver.current_url except: linkurl = "" finally: driver.close() assert expectedurl == linkurl
def studyOne(url): global browser, cookies try: browser.get(url) html = browser.page_source elements = browser.find_elements_by_tag_name("div") for i in range(0, int(60 * 3.5)): element = elements[(i % len(elements))] if element is not None: try: hover = ActionChains(browser).move_to_element(element) hover.perform() except: pass time.sleep(1) finishedPages.add(url) f = open(FINISHED_LIST_FILE, "a+") f.write(url + "\n") f.close() except Exception as e: print(e) restartBrowser()
def test_seo_link(driver): expectedurl = "http://gbh.com.do/servicio/desarrollo/seo-optimizacion-en-motores-de-busqueda/" try: dropdown = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "//li[@id='menu-item-209']"))) hover = ActionChains(driver).move_to_element(dropdown) hover.perform() element = driver.find_element(By.XPATH, "//li[@id='menu-item-227']") element.click() driver.implicitly_wait(2) linkurl = driver.current_url except: linkurl = "" finally: driver.close() assert expectedurl == linkurl
def drag_to(self, ele_or_loc: Union[tuple, WebElement, DrissionElement]) -> bool: """拖拽当前元素,目标为另一个元素或坐标元组 :param ele_or_loc: 另一个元素或相对当前位置 :return: 是否拖拽成功 """ from selenium.webdriver import ActionChains loc1 = self.location actions = ActionChains(self._driver) if isinstance(ele_or_loc, DriverElement): actions.drag_and_drop(self.inner_ele, ele_or_loc.inner_ele) elif isinstance(ele_or_loc, WebElement): actions.drag_and_drop(self.inner_ele, ele_or_loc) elif isinstance(ele_or_loc, tuple): actions.drag_and_drop_by_offset(self.inner_ele, ele_or_loc[0], ele_or_loc[1]) else: raise KeyError('Need WebElement object or coordinate information.') actions.perform() loc2 = self.location if loc1 == loc2: return False return True
def test_certificacion_cableado(driver): expectedurl = "http://gbh.com.do/servicio/soporte/certificacion-de-cableado-estructurado/" try: dropdown = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "//li[@id='menu-item-209']"))) hover = ActionChains(driver).move_to_element(dropdown) hover.perform() element = driver.find_element(By.XPATH, "//li[@id='menu-item-356']") element.click() driver.implicitly_wait(2) linkurl = driver.current_url except: linkurl = "" finally: driver.close() assert expectedurl == linkurl
def click(self, item): try: # 点击事件的几种写法: # self.elements_by(item).click() # self.elements_by(item).send_keys(Keys.ENTER) # self.elements_by(item).send_keys(Keys.SPACE) # self.driver.execute_script("arguments[0].click();", self.elements_by(item)) sleep(0.2) action = ActionChains(self.driver) action.click(self.elements_by(item)) # 鼠标左键点击指定的元素 action.perform() action.release() if item.get("tag_name", '') == 'button' or item.get( "tag_name", '') == 'span' or item.get("tag_name", '') == 'i': self.driver.execute_script("arguments[0].click();", self.elements_by(item)) except selenium.common.exceptions.WebDriverException: t = item["sleep_time"] if item.get("sleep_time", "0") != "0" else be.WAIT_TIME sleep(t) self.driver.execute_script("arguments[0].click();", self.elements_by(item)) return {"result": True}
def test_Sub_Honer(self): element = driver.find_element_by_link_text("User Management") hover = ActionChains(driver).move_to_element(element) hover.perform() time.sleep(1) driver.find_element_by_id("ohrmList_chkSelectAll").click() time.sleep(1) driver.find_element_by_id("ohrmList_chkSelectAll").click() time.sleep(1) element = driver.find_element_by_link_text("Job") hover = ActionChains(driver).move_to_element(element) hover.perform() time.sleep(1) element = driver.find_element_by_link_text("Qualifications") hover = ActionChains(driver).move_to_element(element) hover.perform() time.sleep(1) element = driver.find_element_by_link_text("Configuration") hover = ActionChains(driver).move_to_element(element) hover.perform() time.sleep(1)
def create_new_playlist_teardown(self, playlist_name): """ Deletes the newly created playlist thus getting back to the original state. :param playlist_name: Name of the playlist that was used in the creation of the new playlist """ np = self.SABL.playlist(playlist_name) actions = ActionChains(self.SABL.ret_driver()) actions.context_click(np) actions.perform() actions = ActionChains(self.SABL.ret_driver()) actions.click(self.SABL.delete_button()) actions.perform() actions = ActionChains(self.SABL.ret_driver()) actions.click(self.SABL.red_delete_button()) actions.perform()
def instruct_menu_to_cohort_roster(driver,cohort="pt"): import time time.sleep(0.5) cohort_lead =driver.find_element_by_xpath('/html/body/div[1]/nav/div[1]/ul/li[1]/a') my_cohorts = driver.find_element_by_xpath('//*[@id="js-parentDropdownLink"]') if cohort=="pt": cohort_link = driver.find_element_by_xpath('//*[@id="js-childrenList-141"]/ul/li[1]/a') elif cohort=="ft": cohort_link = driver.find_element_by_xpath('//*[@id="js-sidenavChildrenList-140"]/li[2]/a') # return ft_cohort actions = ActionChains(driver) actions.move_to_element(cohort_lead) actions.pause(.5) actions.click(my_cohorts) actions.pause(.5) actions.click(cohort_link) return actions.perform()
def test_FindClass(self): source = self.driver.find_element_by_id("draggable") target = self.driver.find_element_by_id("droppable") mouse = ActionChains(self.driver).drag_and_drop(source, target) mouse.perform() time.sleep(4) source = self.driver.find_element_by_id("draggable1") target = self.driver.find_element_by_id("droppable1") mouse = ActionChains(self.driver).drag_and_drop(source, target) mouse.perform() time.sleep(4) source = self.driver.find_element_by_id("draggable2") target = self.driver.find_element_by_id("droppable2") mouse = ActionChains(self.driver).drag_and_drop(source, target) mouse.perform() time.sleep(4)
def click(self, by, locator, type="click"): """ 用于模拟鼠标操作,单击/右键/双击 :param by:定位类型 :param locator:元素位置 :param type:点击鼠标的类型,目前支持三种类型,单击,右键,双击 :return: """ ele = self.find(by, locator) action = ActionChains(self._driver) if type == "click": action.click(ele) action.perform() elif type == "context_click": action.context_click(ele) action.perform() elif type == "double_click": action.double_click(ele) action.perform()
def test_config_persists(driver): tt.reset_page(driver) actions = ActionChains(driver) button = driver.find_element_by_id("Config_button") actions.move_to_element(button) actions.click() actions.perform() time.sleep(1.0) actions = ActionChains(driver) checkbox = driver.find_element_by_id("zoom-fonts") actions.move_to_element(checkbox) actions.click() actions.perform() time.sleep(0.5) val = driver.execute_script("return localStorage.getItem('ng.zoom_fonts')") assert val == 'true' actions.perform() # do it again to go back to default (False) val = driver.execute_script("return localStorage.getItem('ng.zoom_fonts')") assert val == 'false'
def category_verification(self): # finding elements by Xpath elem1 = self.driver.find_element_by_xpath( "//a[@href='https://allegro.pl/dzial/elektronika']") hover1 = ActionChains(self.driver).move_to_element(elem1) hover1.perform() elem1.click() wait = WebDriverWait(self.driver, 1) elem2 = self.driver.find_element_by_xpath( "//a[@href='/kategoria/rtv-i-agd']") hover2 = ActionChains(self.driver).move_to_element(elem2) hover2.perform() elem2.click() elem3 = self.driver.find_element_by_xpath( "//a[@href='https://allegro.pl/kategoria/agd-do-zabudowy-67524']") hover3 = ActionChains(self.driver).move_to_element(elem3) hover3.perform() elem3.click() wait = WebDriverWait(self.driver, 1) #checking breadcrumbs elem1_check = self.driver.find_element_by_xpath( "//a[@href='/dzial/elektronika']") elem2_check = self.driver.find_element_by_xpath( "//a[@href='/kategoria/rtv-i-agd']") #checking the final element in breadcrumbs and printing it out elements = [] for elem in self.driver.find_elements_by_xpath( './/span[@itemprop = "name"]'): a = elements.append(elem.text) print elements[3] # creating a condition, if true then print out the sentence in the console if elements[3] == 'AGD do zabudowy': print "Product category and sub-categories are visible in breadcrumbs on the web page."
def mouse_obfuscate(self, p_delay): """ Wait for a specified delay while performing mouse moves and right-clicks. :param p_delay: Delay in seconds. :return: Nothing """ l_max_steps = 5 if p_delay > 5: l_max_steps = int(p_delay) if l_max_steps > 15: l_max_steps = 15 l_delay_steps = random.randint(5, l_max_steps) for i in range(l_delay_steps): l_body = self.m_driver.find_element_by_xpath('//body') l_action = ActionChains(self.m_driver) l_action.move_to_element(l_body) l_action.perform() l_mouse_steps = random.randint(2, 10) # l_mouse_steps = 0 for j in range(l_mouse_steps): l_action = ActionChains(self.m_driver) l_offsetX = random.randint(-self.m_browserWidth / 10, self.m_browserWidth / 10) l_offsetY = random.randint(-self.m_browserHeight / 10, self.m_browserHeight / 10) # self.m_logger.info('{0} Offset: [{1}, {2}]'.format(j, l_offsetX, l_offsetY)) l_action.move_by_offset(l_offsetX, l_offsetY) l_action.perform() time.sleep(.01) l_action = ActionChains(self.m_driver) l_action.context_click() l_action.perform() time.sleep(p_delay / l_delay_steps)
def css_elements(self): # finding elements by css elem1 = self.driver.find_element_by_css_selector("a[data-analytics-click-value='Moda i uroda']") hover1 = ActionChains(self.driver).move_to_element(elem1) hover1.perform() elem1.click() wait = WebDriverWait(self.driver,1) elem2 = self.driver.find_element_by_css_selector("a.m-link[data-analytics-click-custom-index-0='0']") hover2 = ActionChains(self.driver).move_to_element(elem2) hover2.perform() elem2.click() elem3 = self.driver.find_element_by_css_selector("span[data-reactid='28']") hover3 = ActionChains(self.driver).move_to_element(elem3) hover3.perform() elem3.click() wait = WebDriverWait(self.driver,1) #checking breadcrumbs #checking the final element in breadcrumbs by means of inner text and printing it out elem3_check = self.driver.find_element_by_css_selector("h1[class='listing-title ']")
def test_circulo(self): driver = self.driver driver.get("http://www.circuloin.com") time.sleep(3) alquileres = driver.find_element_by_link_text("Alquileres") time.sleep(2) hover = ActionChains(driver).move_to_element(alquileres) hover.perform() alquileres.click() time.sleep(2) departamentos = driver.find_element_by_link_text("Departamentos") time.sleep(2) hover = ActionChains(driver).move_to_element(departamentos) hover.perform() departamentos.click() time.sleep(2) dormitorio = driver.find_element_by_link_text("1 Dormitorio") time.sleep(2) hover = ActionChains(driver).move_to_element(dormitorio) hover.perform() dormitorio.click() time.sleep(2)
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('HRGXFW090') # # driver.switch_to.frame(iframe) SwitchTo(driver).frame(iframe) sleep(2) # 点击新增按钮 driver.find_element_by_xpath( '//*[@id="flowApprove"]//button[@class="btn btn-primary"]').click( ) sleep(2) # 点击新员工tab页签 driver.find_element_by_xpath('//*[@id="staffNewSpan"]').click() # 输入查询数据 driver.find_element_by_xpath('//*[@id="searchValNew"]').send_keys( context.Name.random_name) # 点击查询 driver.find_element_by_xpath('//*[@id="searchBtn1"]/span/i[2]').click() # 点击第一条数据 driver.find_element_by_xpath( '//*[@id="addSignsDialog"]//div[@id="staffNewBody"]//tbody//td[1]//label' ).click() # 点击确定按钮 driver.find_element_by_xpath( '//*[@id="addSignsDialog"]//span[text()="确定"]').click() sleep(1) # 点击右侧的按钮 driver.find_element_by_xpath( '//div[@title="合同开始日期"]/ancestor::fieldset//span[@class="u-form-control-feedback fa fa-calendar"]' ).click() # 点击时间框 driver.find_element_by_xpath( '//*[@id="edit_20180621092332a9Wovv11gh"]//div[@class="u-date-cell current"]' ).click() # 点击输入合同期限 driver.find_element_by_xpath( '//*[@id="20180621092344dfpzcwrr5o"]').send_keys("6") # 选择合同信息 driver.find_element_by_xpath( '//*[@id="edit_20180621092410s9ne5T2NrC"]/div/span[1]').click() # 选择合同 driver.find_element_by_xpath( '//*[@id="refContainer20180621092410s9ne5T2NrC"]//td[text()="0001"]' ).click() # 输入工作地点 driver.find_element_by_xpath( '//*[@id="edit_20180621092415N32bSEPxgw"]/div/span[1]').click() # 选择工作地点 driver.find_element_by_xpath( '//*[@id="refContainer20180621092415N32bSEPxgw"]//td[text()="123"]' ).click() # 点击试用期期限 driver.find_element_by_xpath( '//*[@id="20180621092425fw1gM2Tz5j"]').send_keys(1) # 输入备注内容 # 输入随机内容 paragraph = context.get_paragraph() driver.find_element_by_xpath( '//*[@id="20180621092453tCQEAbvHU1"]').send_keys(paragraph) # 点击保存按钮 driver.find_element_by_xpath( '//*[@id="templatePanel"]/div[4]/button//span[text()="保存"]').click( ) sleep(3) # 点击提交按钮 driver.find_element_by_xpath( '//*[@id="templatePanel"]//button//span[text()="提交"]').click() sleep(2) # 关闭当前页面 driver.switch_to.default_content() sleep(1) driver.find_element_by_xpath( '//*[@id="home_header"]/div/div[3]/ul/li/div').click()
import os import time from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By base_path = os.getcwd() driver = webdriver.Chrome() driver.maximize_window() driver.get("file://%s/注册A.html" % base_path) action = ActionChains(driver) # 在用户文本框上点击鼠标右键 action.context_click(driver.find_element(By.ID, 'userA')) time.sleep(1) action.click(driver.find_element(By.ID, 'userA')) time.sleep(1) # driver.find_element(By.ID, 'userA').send_keys("全选我") # action.double_click(driver.find_element(By.ID, 'userA')) # 执行 action.perform() time.sleep(3) driver.quit()
def assetnonstandard1(self, get_nonstandard): I_CODE = get_nonstandard[0] I_NAME = get_nonstandard[1] P_CLASS = get_nonstandard[2] MTR_DATE = get_nonstandard[3] LBS_RATE = get_nonstandard[4] CP = get_nonstandard[5] # 点击资产管理 self.findxpath_click('//*[@id="navId"]/li[4]/a') # 点击利率型项目资产 self.findxpath_click('//*[@id="floatMenu"]/dl[1]/dd[2]/a') # sleep(1) # 使用显式等待来控制点击新增的时间等待时间 locator = ( By.XPATH, '//div[3]/div[2]/div[2]/div/div/div[1]/span/div/div[1]/div/div/a[2]/span/span/span[1]' ) self.wait_for_click(10, locator) # 点击新增 self.findxpath_click( '//div[3]/div[2]/div[2]/div/div/div[1]/span/div/div[1]/div/div/a[2]/span/span/span[1]' ) # 输入资产代码 self.findxpath_sendkey('//*[@name="assetLBSInfoSub.i_code"]', I_CODE) # 输入资产名称 self.findxpath_sendkey('//*[@name="assetLBSInfoSub.i_name"]', I_NAME) # 选择资产三类 self.findxpath_sendkey( '//fieldset[1]//div[1]/span/div/table[2]/tbody/tr/td[2]/table/tbody/tr/td[1]/input', P_CLASS) sleep(1) self.findxpath_click('//div[2]/div/table/tbody/tr[3]/td/div/span') sleep(1) # 选择核算大类 # 该输入框有aria-invalid="false" 属性,会导致display= none,引起元素不可选中,提示报错:ElementNotVisibleException # self.findxpath_click('//*[@name="assetLBSInfoSub.pClassAct"]') self.findxpath_click( '//fieldset[1]//div[1]/span/div/table[21]/tbody/tr/td[2]/table/tbody/tr/td[2]/div' ) # sleep(1) # 点击核算大类弹窗显示有延迟,添加显式等待 # locator = (By.XPATH, '/html/body/div/div/ul/li[8]') # WebDriverWait(self.driver, 20).until(expected_conditions.element_to_be_clickable(locator)) self.findxpath_click('/html/body/div/div/ul/li[8]') # PCALSS_ACT = self.findxpath('//*[@name="assetLBSInfoSub.pClassAct"]') # 因为北金所债权融资计划在选项的最后,想通过方向键上来选中,但是并未生效,所有的上键均未生效 # PCALSS_ACT.send_keys(Keys.ARROW_UP) # 多次重复操作时,有概率导致动作未生效,需要按八次下,实际只按了六次,故舍弃键盘动作 # PCALSS_ACT.send_keys(Keys.ARROW_DOWN) # PCALSS_ACT.send_keys(Keys.ARROW_DOWN) # PCALSS_ACT.send_keys(Keys.ARROW_DOWN) # PCALSS_ACT.send_keys(Keys.ARROW_DOWN) # PCALSS_ACT.send_keys(Keys.ARROW_DOWN) # PCALSS_ACT.send_keys(Keys.ARROW_DOWN) # PCALSS_ACT.send_keys(Keys.ARROW_DOWN) # PCALSS_ACT.send_keys(Keys.ARROW_DOWN) # PCALSS_ACT.send_keys(Keys.ENTER) # sleep(1) # 输入到期日 self.findxpath_sendkey('//*[@name="fixedInstrumentSub.mtr_date"]', MTR_DATE) # 点击利率调整 self.findxpath_click( '//fieldset[2]/div/span/div/div[2]/span/div/table[4]/tbody/tr/td[2]/div/div/div/a/span/span/span[1]' ) # 输入利率:双击输入框→输入利率 rate = self.findxpath( '//div[3]/span/div/div/div[2]/div/table/tbody/tr/td[3]/div') action = ActionChains(self.driver) action.double_click(rate) action.perform() self.findxpath_sendkey('//*[@name="volume"]', LBS_RATE) self.findxpath_click( '//div[3]/span/div/div/div[1]/div[2]/span/div/a[1]/span/span/span[2]' ) self.findxpath_click( '/html/body/div[last()-1]/div[1]/div/div/div/div[2]/img') # 输入初始本金 self.findxpath_sendkey('//*[@name="fixedInstrumentSub.amount"]', CP) # 点击保存 self.findxpath_click( '//div[3]/div[2]/div[2]/div/div[2]/div[2]/div/div/a[1]/span/span/span[1]' ) # 点击确定 self.findxpath_click('//*[@id="button-1005-btnIconEl"]') # 点击返回 self.findxpath_click( '//div[3]/div[2]/div[2]/div/div[2]/div[2]/div/div/a[3]/span/span/span[1]' ) # 切换未生效列表 self.findxpath_click('//*[@name="isEffctive"]') ISEFFCTIVE = self.findxpath('//*[@name="isEffctive"]') ISEFFCTIVE.send_keys(Keys.ARROW_DOWN) ISEFFCTIVE.send_keys(Keys.ENTER) # 查询对应代码 self.findxpath_sendkey( '//div[3]/div[2]/div[2]/div/div[1]/div[1]//div[2]//table[2]//tr/td[2]//tr/td[1]/input', I_CODE) searchlib = self.findxpath( '//div[3]/div[2]/div[2]/div/div[1]/div[1]//div[2]//table[2]//tr/td[2]//tr/td[1]/input' ) searchlib.send_keys(Keys.ARROW_DOWN) searchlib.send_keys(Keys.ENTER) # 输入代码后有一个下拉选择的列表,当列表遮挡下一步的按钮时,操作将会被拦截并提示错误:ElementClickInterceptedException # 下一步操作有概率出现错误 self.findxpath_click( '//div[3]/div[2]/div[2]/div/div[1]/div[1]//div[3]/div/div/a[1]/span/span/span[1]' ) sleep(1) # 选中对应资产 self.findxpath_click( '//div[3]/div[2]/div[2]/div/div[1]/div[2]/div/div/div[1]/div[2]/div/table/tbody/tr/td[1]/div/div' ) # self.findxpath_click('//div[3]/div[2]/div[2]/div/div[1]/div[2]//div[1]/div[2]/div/table/tbody/tr/td[2]/div') # 点击复核按钮 self.findxpath_click( '//div[3]/div[2]/div[2]/div/div[1]/div[1]//div[1]/div/div/a[7]/span/span/span[1]' ) # 点击确定 self.findxpath_click('//*[@id="button-1005-btnIconEl"]') return True
def init(self, car_serial, car_model, vin): """ 输入车系,车型,VIN号,初始化远程监控的环境 :return: True 成功, False 失败 """ try: self.browser.get( "http://pv-terminal-dev-admin.gacicv.com/remoteMonitoring/monitoringSignal" ) self.browser.implicitly_wait(3) # 输入车系 sleep(1) s_ls = self.browser.find_elements_by_xpath( "//div[@class='el-select-dropdown el-popper']//ul/li") print(len(s_ls)) for s in s_ls: if s.get_attribute('innerText').strip() == car_serial: i1 = self.browser.find_element_by_xpath( "//div[@class='monitoringSignal']//div[" "@class='el-select'][1]//input") i1.click() action = ActionChains( self.browser).move_to_element(s).click() sleep(0.5) action.perform() break else: print("服务器不支持该车系") return False # 输入车型 sleep(1) m_ls = self.browser.find_elements_by_xpath( "//div[@class='el-select']/div[@class='el-select-dropdown " "el-popper']//ul/li") print(len(m_ls)) for m in m_ls: if m.get_attribute('innerText').strip() == car_model: i2 = self.browser.find_element_by_xpath( "//div[@class='monitoringSignal']//div[" "@class='el-select'][2]//input") i2.click() action = ActionChains( self.browser).move_to_element(m).click() sleep(0.5) action.perform() break else: print("车系不支持该车型") return False # 输入VIN号 i3 = self.browser.find_element_by_xpath( "//div[@class='el-input']/input") i3.send_keys(vin) self.browser.find_element_by_xpath( "//label[@class='write_vin']").click() self.__update_signal_indexes() except (WebDriverException, NoSuchElementException) as e: print(e.message) else: return True finally: return False
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('HRXC030010') # # driver.switch_to.frame(iframe) SwitchTo(driver).frame(iframe) sleep(2) # 点击新增方案按钮 driver.find_element_by_xpath( '//div[@class="fn-sort"]//button[4]').click() sleep(2) # 输入方案名称 num = random.randint(100, 999) name = "方案名称{}".format(num) 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() sleep(1) # 点击选择条目 driver.find_element_by_xpath( '//div[@class="ref-content-wrap ref-content-grid-wrap"]//tbody//tr[1]').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//span[@class="el-input__suffix"]').click() # 选择期间条目 driver.find_element_by_xpath('//div[@class="el-col el-col-16"]//tbody//tr[1]').click() # 点击确定 driver.find_element_by_xpath( '//div[@class="op-button"]/button[2]').click() sleep(1) # 输入方案说明 driver.find_element_by_xpath('//textarea').send_keys("方案说明信息09929") # 点击保存按钮 driver.find_element_by_xpath( '//div[@class="pp-container container-edit"]//div[@class="in-bottom"]//button[2]').click() sleep(0.75) self.assertEqual("操作成功!", driver.find_element_by_xpath('//p[text()="操作成功!"]').text) # 点击修改方案 driver.find_element_by_xpath('//div[@class="pp-header"]//button[3]').click() sleep(2) # 点击保存按钮 driver.find_element_by_xpath( '//div[@class="pp-container container-edit"]//div[@class="in-bottom"]//button[2]').click() sleep(0.75) self.assertEqual("操作成功!", driver.find_element_by_xpath('//p[text()="操作成功!"]').text) # 点击删除方案 driver.find_element_by_xpath('//div[@class="pp-header"]//button[2]').click() sleep(2) # 点击确定 driver.find_element_by_xpath('//div[@class="el-message-box"]//button[2]').click() sleep(1) 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()
def hover(self, element): action = ActionChains(self.driver) el = self.find(element) action.move_to_element(el) action.perform()
# 5.商品分类 driver.find_element_by_id("1").click() driver.find_element_by_id("2").click() driver.find_element_by_id("6").click() driver.find_element_by_id("7").click() # 第一种实现方法:点击6,在点击7 # 双击的操作实现方法,适用于所有特殊元素操作:ActionChains类 ActionChains(driver).double_click(driver.find_element_by_id("7")).perform() # 第二种实现方法 # driver.find_element_by_id("jiafen").click() # 6.商品品牌 brand = driver.find_element_by_name("brand_id") Select(brand).select_by_value('1') # 7.点击商品图册 driver.find_element_by_link_text("商品图册").click() # driver.find_element_by_css_selector("rt_rt_1bvor7t99g7d1nr9unk5pe1sgg8") driver.find_element_by_name("file").send_keys("D:/TU/baby.jpg") # 输入图片路径 # driver.find_element_by_name("file").send_keys("D:/TU/1.jpg") # 对滚动条的处理,用于窗口未最大化,点击不到按钮的时候 ac = ActionChains(driver) for i in range(10): ac.send_keys(Keys.ARROW_RIGHT) ac.perform() driver.find_element_by_css_selector( ".uploadBtn.state-finish.state-ready").click() # 8.确定弹框 time.sleep(3) driver.switch_to.alert.accept() # 窗口没有最大化会报错,将窗口最大化就可以了或者加上滚动条的处理 driver.find_element_by_class_name("button_search").click()
def goto_screen(driver, screen_name): log = logging.getLogger(__name__) wait = WebDriverWait(driver, 8) if screen_name not in ITAU_NAVIGATION: log.critical( "There is no configured navigation for the screen '{}'.".format( screen_name)) return False log.info("Navigating to screen {} ...".format(screen_name)) switch_to_frame(driver, 'MENU') nav = ITAU_NAVIGATION[screen_name] # Try to navigate through search box first search_found = False if nav['search'] is not None: log.info("Locating search field...") try: search_element = wait.until( EC.visibility_of_element_located( (By.XPATH, '//input[@id="input-busca"]'))) except TimeoutException: log.info('Search field not found: //input[@id="input-busca"]') # return False else: log.info("Search field was successfully found!") search_found = True # If ITAU search-navigation element was found, use it, faster. if search_found: search_element.click() search_element.clear() search_element.send_keys(nav['search']) hover = ActionChains(driver).move_to_element(search_element) hover.perform() time.sleep(1) search_element.click() time.sleep(1) try: target = '//div[contains(text(),"{}")]/parent::a'.format( nav['search'][-30:]) log.info("Waiting for element to appear: {}".format(target)) link = wait.until(EC.element_to_be_clickable((By.XPATH, target))) except TimeoutException: log.error('Unable to locate element: {}'.format(target)) # return False else: log.info("Clicking on link {}".format(target)) link.click() return True elif nav['menu'] is not None: # Navigate by MENU button menu_xpath = '//a[@class="btn-nav"][contains(text(),"menu")]' log.info("Trying to locate MENU: {}".format(menu_xpath)) try: menu_element = wait.until( EC.visibility_of_element_located((By.XPATH, menu_xpath))) except TimeoutException: log.critical('Unable to locate MENU: {}'.format(menu_xpath)) return False log.info("MENU successfully found! hovering over it...") hover = ActionChains(driver).move_to_element(menu_element) hover.perform() time.sleep(1) link_xtag = '//a[text()="{}"]'.format(nav['menu'][0]) log.debug("Trying to locate link {} ...".format(link_xtag)) try: menu_element = wait.until( EC.element_to_be_clickable((By.XPATH, link_xtag))) except NoSuchElementException: log.critical("Unable to locate menu item: {}".format(link_xtag)) return False menu_element.click() time.sleep(5) driver.switch_to.default_content() link_xtag = '//a[contains(text(),"{}")]'.format(nav['menu'][1]) log.debug("Trying to locate element: {}".format(link_xtag)) try: link = wait.until(EC.element_to_be_clickable( (By.XPATH, link_xtag))) except NoSuchElementException: log.critical("Unable to locate link: {}".format(link_xtag)) return False log.debug("Link found! clicking on it...") link.click() return True else: log.critical( 'Unable to locate search field: //input[@id="input-busca"].') return False
def send_request(self): counter = User().get_day_counter() page_number = 0 while counter < self.limit: # Parse filter url par = urlparse.parse_qs(urlparse.urlparse(self.sales_url).query) change_param_url = self.sales_url.replace( 'count=' + par['count'][0], 'count=' + str(50)) filter_url = change_param_url.replace('start=' + par['start'][0], 'start=' + str(page_number)) # ----------------- self.chrome.get(filter_url) time.sleep(5) list = self.chrome.find_elements( By.XPATH, ".//ul[@id='results-list']/li//div[@class='content-wrapper']") if list: for item in list: verify_connect = item.find_elements( By.XPATH, ".//div[@class='secondary-actions-container']" "//ul[@class='dropdown']/li/button") buttons_name = [] for v in verify_connect: buttons_name.append(v.get_attribute('class')) if "action connect" not in buttons_name: continue element = item.find_element( By.XPATH, ".//div[@class='secondary-actions-container']") hov = ActionChains(self.chrome).move_to_element(element) hov.perform() time.sleep(1) item.find_element( By.XPATH, ".//button[@class='action connect']").click() time.sleep(3) try: # Cancel if need enter required email address try: self.chrome.find_element( By.XPATH, './/input[@id="connect-email-input"]') self.text.insert('end', "Requires email\n") self.text.see('end') time.sleep(2) self.chrome.find_element( By.XPATH, './/button[@class="dialog-close"]').click() time.sleep(2) continue except: pass # -------------------------------------------- full_name = self.chrome.find_element( By.CLASS_NAME, 'fullname').text # Send message text_field = self.chrome.find_element( By.XPATH, ".//textarea[@id='connect-message-content']") text_field.clear() time.sleep(2) # Get First Name if '%s' in self.sales_message_text: z = full_name.split(' ') if '.' in z[0]: z[0] = z[0] + ' ' + z[1] text = self.sales_message_text % z[0].title() else: text = self.sales_message_text z = text.split('\n') for i in z: text_field.send_keys(i) text_field.send_keys(Keys.SHIFT + Keys.ENTER) time.sleep(1) # ------------- time.sleep(2) # ------------ # self.chrome.find_element(By.XPATH, './/button[@class="dialog-close"]').click() self.chrome.find_element( By.XPATH, './/button[text()="Send Invitation"]').click() self.text.insert('end', "%s was invited.\n" % full_name) self.text.see('end') User().create(full_name) time.sleep(random.randrange(20, 40)) counter += 1 except Exception as e: self.text.insert('end', "Yonchi joked: {}\n".format(e)) self.text.see('end') continue if counter == self.limit: self.text.insert('end', "Yonchi finished work !\n") self.text.see('end') counter += 1000000 break page_number += 50 if counter != 0 and counter % 10 == 0 and counter < 1000000: self.text.insert('end', "Current added -> {}\n".format(counter)) self.text.see('end') else: self.text.insert('end', "Yonchi finished work !\n") self.text.see('end') counter += 1000000 self.text.insert('end', "Yonchi used all limit !\n") self.text.see('end') self.chrome.close()
profile_info.append(name_h1.text) # парсинг постов print("Парсю посты") post_divs = "//div[@class='rq0escxv l9j0dhe7 du4w35lb d2edcug0 hpfvmrgz gile2uim buofh1pr g5gj957u aov4n071 oi9244e8 bi6gxh9e h676nmdw aghb5jc5']/div" scroll_to_down(post_divs, 2) last_post = driver.find_element_by_xpath( "//div[@class='rq0escxv l9j0dhe7 du4w35lb d2edcug0 hpfvmrgz gile2uim buofh1pr g5gj957u aov4n071 oi9244e8 bi6gxh9e h676nmdw aghb5jc5']/div[last()]" ) time_post = last_post.find_element_by_css_selector( 'a[class="oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl gmql0nx0 gpro0wi8 b1v8xokw"]' ) hover = ActionChains(driver).move_to_element(time_post) hover.perform() time.sleep(1) try: time_full = driver.find_element_by_css_selector( 'span[class="d2edcug0 hpfvmrgz qv66sw1b c1et5uql gk29lw5a a8c37x1j keod5gw0 nxhoafnm aigsh9s9 tia6h79c fe6kdd0r mau55g9w c8b282yb iv3no6db e9vueds3 j5wam9gi knj5qynh oo9gr5id hzawbc8m"]' ) except: try: time_icon = last_post.find_element_by_css_selector( 'span[class="tojvnm2t a6sixzi8 abs2jz4q a8s20v7p t1p8iaqh k5wvi7nf q3lfd5jv pk4s997a bipmatt0 cebpdrjk qowsmv63 owwhemhu dp1hu0rb dhp61c6y iyyx5f41"]' ) prelast_post = driver.find_element_by_xpath( "//div[@class='rq0escxv l9j0dhe7 du4w35lb d2edcug0 hpfvmrgz gile2uim buofh1pr g5gj957u aov4n071 oi9244e8 bi6gxh9e h676nmdw aghb5jc5']/div[last()-1]" ) time_post = prelast_post.find_element_by_css_selector( 'a[class="oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl gmql0nx0 gpro0wi8 b1v8xokw"]'