def when_i_drag_pill_from_time1_to_time2(step, pill, time1, time2): # get the data id for this pill pill = find_pill(pill) assert pill is not None, "No pill named %s found." % pill draggable = pill.find_element_by_css_selector( "div.pill-image span.draggable") assert draggable is not None, ( "This pill is not constructed properly: %s" % pill) data_id = draggable.get_attribute("data-id") bucket = get_bucket(time1) assert bucket is not None, ( "Source time slot must be specified as day or evening. " "No time slot called %s found" % time) dest = get_bucket(time2) assert dest is not None, ( "Destination time slot must be specified as day or evening. " "No time slot called %s found" % time) a = bucket.find_elements_by_css_selector('span.trashable') assert len(a) > 0, ( "Expected at least 1 pill in bucket %s, instead it " "contains %s pills" % (bucket, len(a))) action = False for dropped in a: if (data_id == dropped.get_attribute("data-id")): # found it, now, drag it to the second bucket action_chains = ActionChains(world.browser) action_chains.drag_and_drop(dropped, dest).perform() action = True assert action, ( "No dropped pills named %s found in %s slot" % (pill, time1))
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 put_element_on_grid(self, type_str): '''find 'type_str' in the Library, drag and drop it onto the grid''' browser = self.browser grid = browser.find_element_by_xpath('//div[@id="-dataflow"]') for retry in range(3): try: objtype = self.find_library_button(type_str) chain = ActionChains(browser) chain.click_and_hold(objtype) chain.move_to_element_with_offset(grid, 10, 10).perform() except StaleElementReferenceException: if retry < 2: logging.warning('put_element_on_grid %s:' ' StaleElementReferenceException', type_str) else: raise else: break self.check_highlighting(grid, True, "Grid") self.release(chain) # deal with the modal dialog name = NameInstanceDialog(self).create_and_dismiss() # make sure it is on the grid self.ensure_names_in_workspace([name], "Dragging '" + type_str + "' to grid did not produce a new element on page") return name
def drag_scroll_by_css(browser, offset_x, offset_y): scroll, height = wait_element_present(browser) action = ActionChains(browser) try: action.click_and_hold(scroll[0]).move_by_offset(int(offset_x), int(offset_y) + 1).release().perform() except AssertionError: drag_scroll_by_css(browser, offset_x, offset_y)
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 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_can_move_block_from_one_container_to_another(live_server, browser, admin_user): page = factories.FancyPageFactory(node__name='Home') main_container = page.containers.all()[0] layout = factories.TwoColumnLayoutBlockFactory(container=main_container) browser.visit(live_server.url + page.get_absolute_url()) right = layout.containers.get(name='right-container') left = layout.containers.get(name='left-container') moving_block = factories.TextBlockFactory(container=right) factories.TextBlockFactory(container=right) factories.TextBlockFactory(container=left) browser.visit(live_server.url + page.get_absolute_url()) browser.find_by_css('#editor-handle').first.click() source = browser.find_by_css( '#block-{} div.move'.format(moving_block.uuid)).first chain = ActionChains(browser.driver) chain.drag_and_drop_by_offset(source._element, -600, 200).perform() time.sleep(5) assert right.blocks.count() == left.blocks.count() == 1 assert main_container.blocks.count() == 2 main_block_ids = [b.uuid for b in main_container.blocks.all()] assert main_block_ids == [layout.uuid, moving_block.uuid]
def test_LoginRead(self):#第二种方法,见main里的注释 cdr=self.cdr Url=self.Url cdr.get(Url) #cdr.implicitly_wait(5) WebDriverWait(cdr,10).until(lambda cdr:cdr.find_element_by_xpath(".//*[@id='J_connect']/div[2]/div/div/span/a[2]")) fopen=open(r".\something\username.txt","r") for us in fopen:#------这里是从文件里进行读取 time.sleep(2) cdr.find_element_by_xpath(".//*[@id='J_connect']/div[2]/div/div/span/a[2]").click()#点击登录 WebDriverWait(cdr,10).until(lambda cdr:cdr.find_element_by_id("email_login")) cdr.find_element_by_id("email_login").click()#点击使用邮箱登陆 print cdr.find_element_by_id("email_login").get_attribute("title") #输入用户名密码 time.sleep(2) cdr.find_element_by_id("login_email").send_keys(us) print "登录用户名为:"+us cdr.find_element_by_id("login_password").send_keys("123456") cdr.find_element_by_id("remember_me").click()#去掉记住登陆 checkbox #点击登录按钮 cdr.find_element_by_id("login").click() time.sleep(5) #鼠标移动到 头像旁边的下落箭头上 action=ActionChains(cdr) action.move_to_element(cdr.find_element_by_xpath("//div[@class='tr']/div/span[2]")).perform() #下拉菜单点击 退出帐号 cdr.find_element_by_xpath("//div[@class='tr']/div/span[3]/ul/li[4]/a").click() fopen.close()
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 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 test_history(self): ''' 1. Get the outer div id of the activecode component 2. Find the run button using its class name 3. Run the example 4. Check the output from the ac_output element :return: ''' self.driver.get(self.host + "/index.html") t1 = self.driver.find_element_by_id("test1") self.assertIsNotNone(t1) rb = t1.find_element_by_class_name("run-button") self.assertIsNotNone(rb) rb.click() ta = t1.find_element_by_class_name("cm-s-default") self.assertIsNotNone(ta) self.driver.execute_script("""edList['test1'].editor.setValue("print('GoodBye')")""") WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "run-button"))) rb.click() output = t1.find_element_by_class_name("ac_output") self.assertEqual(output.text.strip(),"GoodBye") move = ActionChains(self.driver) slider = t1.find_element_by_class_name("ui-slider") width = slider.size['width'] slider = t1.find_element_by_class_name("ui-slider-handle") move.click_and_hold(slider).move_by_offset(-width,0).release().perform() rb.click() output = t1.find_element_by_class_name("ac_output") self.assertEqual(output.text.strip(), "Hello World")
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 drag_element_by_offset_class_name(browser, className, index, rightOrLeft, offset): elements = find_elements_by_class(browser, className) action_chains = ActionChains(browser) if str(rightOrLeft) == "left": action_chains.drag_and_drop_by_offset(elements[int(index) - 1], -int(offset), 0).perform() else: action_chains.drag_and_drop_by_offset(elements[int(index) - 1], int(offset), 0).perform()
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 setup_google_driver(): driver = webdriver.Firefox() driver.get('http://google.com') time.sleep(0.2) #driver.maximize_window() time.sleep(3) driver.get('http://google.com/preferences') time.sleep(2) radios = driver.find_elements_by_css_selector('div.jfk-radiobutton') radio = radios[-1] radio.click() time.sleep(1.2) slider = driver.find_element_by_css_selector('div.goog-slider-scale') dims = slider.size width = dims['width'] move = ActionChains(driver) slider2 = driver.find_element_by_css_selector('div.goog-slider-scale') for i in range(4): time.sleep(0.1) move.click_and_hold(slider2).move_by_offset(width//9,0).release().perform() move.click_and_hold(slider2).move_by_offset(width//2,0).release().perform() time.sleep(1.5) driver.switch_to_default_content() #save settings elems = driver.find_elements_by_id('form-buttons') elems[0].find_elements_by_tag_name('div')[0].click() alert = driver.switch_to_alert() time.sleep(0.91) alert.accept() time.sleep(1) return driver
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 test_search_in_python_org(self): driver = self.driver driver.implicitly_wait(10) actions = ActionChains(driver) driver.get("http://localhost:8080") ens = driver.find_element_by_class_name('ens') ens.click() 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 == 'Value': button.click() break graph = driver.find_element_by_css_selector(".graph") actions.drag_and_drop_by_offset(graph, xoffset=-15, yoffset=15).perform() play_button = driver.find_element_by_id('VIZ.SimControl.play_button') play_button.click() time.sleep(3) line = driver.find_element_by_css_selector("path.line:nth-child(1)") data = line.rect print data test_val = data['height'] + data['width'] assert test_val != 0 block = driver.find_element_by_id("BlockTestCompletion")
def test_en_classify_products_function_drag_and_drop(self): driver = self.driver gb_login(self) driver.get(self.base_url + "/ev/classifyproducts") driver.find_element_by_xpath("//li[@id='categoryCol_category514']/div/span").click() # Verify process missing. try: self.assertTrue( self.is_element_present( By.CSS_SELECTOR, "#categoryCol_subcategory515 > div.itemContent.subCategoryBg > div.handle" ) ) except AssertionError as e: self.verificationErrors.append(str(e)) try: self.assertTrue( self.is_element_present( By.CSS_SELECTOR, "#categoryCol_category517 > div.categoryBg.itemContent > div.blockText" ) ) except AssertionError as e: self.verificationErrors.append(str(e)) element = driver.find_element_by_css_selector( "#categoryCol_subcategory515 > div.itemContent.subCategoryBg > div.handle" ) target = driver.find_element_by_css_selector( "#categoryCol_category517 > div.categoryBg.itemContent > div.blockText" ) action_chains = ActionChains(driver) action_chains.drag_and_drop(element, target)
def close_slider(self, by_area=0): if by_area: btn_close = self.driver.find_element_by_class_name(self.CLOSE_AREA) actions = ActionChains(self.driver) actions.move_to_element_with_offset(btn_close, 0, 0).click().perform() else: btn_close = self.driver.find_element_by_class_name(self.CLOSE_CLASS) btn_close.click()
def find_text(self, text): #click the 'find' button, and enter text. Not yet functional self('editor_find_button').click() alert = self.browser.switch_to_alert() chain = ActionChains(alert) chain.send_keys(text).perform() chain.send_keys(Keys.RETURN).perform() return
def input_edit_driver(self, driver_pathname): """ Return :class:`DriverPage` associated with the input port. """ chain = ActionChains(self.browser) chain.context_click(self.input_port).perform() time.sleep(0.5) self('edit_driver').click() editor_id = 'CE-%s' % driver_pathname.replace('.', '-') return DriverPage(self.browser, self.port, (By.ID, editor_id))
def setInputText(self, name, value): textArea = self.workflow_input.find_element_by_xpath( './*[@data-input-name="{0}"]//textarea'.format(name) ) action_chains = ActionChains(self.portal.browser) action_chains.move_to_element(textArea).click().send_keys( Keys.BACK_SPACE*len(textArea.text)+str(value) ).perform()
def test_drag(self): global driver element = driver.find_element_by_id("draggable") target = driver.find_element_by_id("div2") actions = ActionChains(driver) actions.drag_and_drop(element, target).perform() self.assertEqual("You are definitely not a bot!", driver.find_element_by_id("message").text)
def resize_column(browser, column_name, left_or_right, offsetx): action_chains = ActionChains(browser) element = browser.execute_script( "return $('.ember-table-header-container .ember-table-content:contains(" + column_name + ")').parent().parent().children()[1]") if left_or_right == "left": action_chains.drag_and_drop_by_offset(element, -int(offsetx), 0).release().perform() else: action_chains.drag_and_drop_by_offset(element, int(offsetx), 0).release().perform()
def command_ctrl_with_click(browser, col_name, command_or_ctrl): chains = ActionChains(browser) element = browser.execute_script( "return $('.ember-table-header-container .ember-table-content:contains(" + col_name + ")').parent().parent()") if command_or_ctrl == "command": chains.key_down(Keys.COMMAND).click(element[0]).key_up(Keys.COMMAND).perform() elif command_or_ctrl == "control": chains.key_down(Keys.CONTROL).click(element[0]).key_up(Keys.COMMAND).perform()
def click(self, element): # Although elements have a click method, it seems to play up, possibly # when browser loses focus. Search for "selenium missing click" to get # an idea of the problem. Most complaints are on IE, but Chrome seems # susceptible as well. The incantation below, with the move operation # before the click, seems to work more reliably. action_chains = ActionChains(self.browser) action_chains.move_to_element(element).click().perform()
def test_search_in_python_org(self): driver = self.driver action_chains = ActionChains(driver) driver.get("http://localhost:8080") graph_elements = driver.find_elements_by_class_name("graph") for e in graph_elements: action_chains.drag_and_drop_by_offset(e, xoffset=2, yoffset=2).perform()
def test_search_in_python_org(self): driver = self.driver driver.get("http://localhost:8000") assert "nengo" in driver.page_source assert "default.py" in driver.page_source element = driver.find_element_by_id("ensemble") action_chains = ActionChains(driver) action_chains.drag_and_drop_by_offset(element, xoffset=100, yoffset=200).perform()
def reorder_column_with_offset(browser, css, index, rightOrLeft, offset): columnsHeader = find_elements_by_css(browser, css) action_chains = ActionChains(browser) if str(rightOrLeft) == "left": action_chains.click_and_hold(columnsHeader[int(index) - 1]).move_by_offset(-int(offset), 0).move_by_offset(10, 0).release().perform() else: action_chains.click_and_hold(columnsHeader[int(index) - 1]).move_by_offset(int(offset), 0).move_by_offset(-10, 0).release().perform()
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()
select.deselect_all() #to get all available options options = Select.options #once you filled a form use can submit by driver.find_element_by_id('submit').click() (or) element.submit() #for Drag and Drop element = driver.find_element_by_name("source") //here is the source file target = driver.find_element_by_name("target") //here is ur destination or drop ur file from selenium.webdriver import ActionChains //to do this drag and drop import this module action_chains = ActionChains(driver) action_chains.drag_and_drop(element, target).perform() #You can also swing from frame to frame (or into iframes): driver.switch_to_frame("frameName") #Once we are done with working on frames, we will have to come back to the parent frame which can be done using: driver.switch_to_default_content() #pop-up dialogs alert = driver.switch_to_alert() #we can move backward and forward our browser history driver.get('https://google.com') driver.back()
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()
def get_electronics(self): action = ActionChains(self.drive) hover = self.drive.find_element_by_xpath(self.hover_electronics) return action.move_to_element(hover).perform()
def crawl_good_data(self): # 对天猫商品数据进行爬虫 self.browser.get("https://list.tmall.com/search_product.htm?q=羽毛球") err1 = self.browser.find_element_by_xpath( "//*[@id='content']/div/div[2]").text err1 = err1[:5] if (err1 == "喵~没找到"): print("找不到您要的") return try: self.browser.find_element_by_xpath("//*[@id='J_ComboRec']/div[1]") err2 = self.browser.find_element_by_xpath( "//*[@id='J_ComboRec']/div[1]").text # print(err2) err2 = err2[:5] if (err2 == "我们还为您"): print("您要查询的商品书目太少了") return except: print("可以爬取这些信息") # 获取天猫商品总共的页数 page_total = self.search_toal_page() print("总共页数" + page_total) # 遍历所有页数 for page in range(2, int(page_total)): # 等待该页面全部商品数据加载完毕 good_total = self.wait.until( EC.presence_of_element_located( (By.CSS_SELECTOR, '#J_ItemList > div.product > div.product-iWrap'))) # 等待该页面input输入框加载完毕 input = self.wait.until( EC.presence_of_element_located(( By.CSS_SELECTOR, '.ui-page > div.ui-page-wrap > b.ui-page-skip > form > input.ui-page-skipTo' ))) # 获取当前页 now_page = input.get_attribute('value') print("当前页数" + now_page + ",总共页数" + page_total) # 获取本页面源代码 html = self.browser.page_source # pq模块解析网页源代码 doc = pq(html) # 存储天猫商品数据 good_items = doc('#J_ItemList .product').items() # 遍历该页的所有商品 for item in good_items: good_title = item.find('.productTitle').text().replace( '\n', "").replace('\r', "") good_status = item.find('.productStatus').text().replace( " ", "").replace("笔", "").replace('\n', "").replace('\r', "") good_price = item.find('.productPrice').text().replace( "¥", "").replace(" ", "").replace('\n', "").replace('\r', "") good_url = item.find('.productImg').attr('href') print(good_title + " " + good_status + " " + good_price + " " + good_url + '\n') # 精髓之处,大部分人被检测为机器人就是因为进一步模拟人工操作 # 模拟人工向下浏览商品,即进行模拟下滑操作,防止被识别出是机器人 self.swipe_down(2) # 翻页,下一页 self.next_page(page) # 等待滑动验证码出现,超时时间为5秒,每0.5秒检查一次 # 大部分情况不会出现滑动验证码,所以如果有需要可以注释掉下面的代码 # sleep(5) WebDriverWait(self.browser, 5, 0.5).until( EC.presence_of_element_located( (By.ID, "nc_1_n1z"))) # 等待滑动拖动控件出现 try: swipe_button = self.browser.find_element_by_id( 'nc_1_n1z') # 获取滑动拖动控件 # 模拟拽托 action = ActionChains(self.browser) # 实例化一个action对象 action.click_and_hold( swipe_button).perform() # perform()用来执行ActionChains中存储的行为 action.reset_actions() action.move_by_offset(580, 0).perform() # 移动滑块 except Exception as e: print('get button failed: ', e)
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver import ActionChains from webdriver_manager.chrome import ChromeDriverManager import time driver = webdriver.Chrome(ChromeDriverManager().install()) driver.implicitly_wait(10) driver.get("https://jqueryui.com/resources/demos/droppable/default.html") source = driver.find_element(By.ID, 'draggable') target = driver.find_element(By.ID, 'droppable') act_chains = ActionChains(driver) #act_chains.drag_and_drop(source, target).perform() act_chains.click_and_hold(source).move_to_element(target).release().perform()
#impot actionchains #.perform() #move_to_element(whichever you wanna click) from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select import time driver = webdriver.Chrome(executable_path="/home/divya/Documents/cdn") driver.get("https://www.toolsqa.com/selenium-webdriver/mouse-hover-action/") driver.maximize_window() tutorial = driver.find_element_by_xpath( "/html/body/div[1]/div[1]/header/nav/ul/li[2]/a/span/span") prog_lang = driver.find_element_by_xpath( "/html/body/div[1]/div[1]/header/nav/ul/li[2]/ul/li[9]/a/span/span") python = driver.find_element_by_xpath( "/html/body/div[1]/div[1]/header/nav/ul/li[2]/ul/li[9]/ul/li[3]/a/span/span" ) actions = ActionChains(driver) actions.move_to_element(tutorial).move_to_element(prog_lang).move_to_element( python).click().perform() #c= actions.move_to_element(tutorial)#.move_to_element(prog_lang).move_to_element(python).click().perform( #time.sleep(2) #d= c.move_to_element(prog_lang) #time.sleep(2) #e = d.move_to_element(python).click().perform()
def test_number1(self): """智能注册_自助商标跳转测试""" # logging.basicConfig(filename='../LOG/' + __name__ + '.log', # format='[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]', level=logging.DEBUG, # filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p') dl = DengLuPage(self.driver) # 官方推荐有find_element(By.*(""))代替find_element_by_*("") # self.driver.find_element_by_id() # self.driver.find_element() dl.login() time.sleep(2) ActionChains(self.driver).move_to_element( self.driver.find_element_by_css_selector( "body > div.section-banner > div.public-navbar > div > div > h3 > span" )).perform() time.sleep(2) ActionChains(self.driver).move_to_element( self.driver.find_element_by_css_selector( "body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(1) > h3 > a" )).perform() ActionChains(self.driver).release() self.driver.find_element_by_css_selector( "body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(1) > div > dl:nth-child(3) > dd > a:nth-child(3)" ).click() # 获取打开的多个窗口句柄 windows = self.driver.window_handles # 切换到当前最新打开的窗口 self.driver.switch_to.window(windows[-1]) time.sleep(2) self.driver.set_window_size(1920, 1080) self.assertIn("商标智能注册|商标注册查询|商标注册网-权大师", self.driver.title) print(self.driver.title) self.driver.find_element_by_css_selector( "body > div.section-product.width1200 > dl > dd > div.cont-serviceItems > table > tbody > tr > td.td-cont > ul > li:nth-child(3)" ).click() for a in self.driver.find_elements_by_css_selector("#total-price"): print("费用总计:" + a.text) # aa=a.text self.driver.find_element_by_css_selector( "body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow" ).click() time.sleep(2) self.driver.find_element_by_css_selector( "body > div.recommend-help > i").click() # body > div.recommend-help > i ss = "小米" self.driver.find_element_by_name("brandName").send_keys( "{}".format(ss)) print("商标名称:{}".format(ss)) self.driver.find_element_by_css_selector( "#create-tuyang > label.label.checked").click() self.driver.find_element_by_css_selector( "body > div.register-wrap.brandinfo-wrap > div.brand-info-wrap.show1.form-wrap > ul > li.brand-upload > div > div.brand-upload-wrap > div.zidongdong-create > ul > li > a" ).click() time.sleep(5) self.driver.find_element_by_css_selector( "#selectCategoryType > label:nth-child(2)").click() self.driver.execute_script("window.scrollBy(0,1200)") # 滑动滚动条 suiji = random.randint(2, 45) time.sleep(2) self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-left > ul > li:nth-child({}) > span" .format(suiji)).click() time.sleep(2) self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-left > ul > li.list.open > div:nth-child(2) > span" ).click() self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(1) > span" ).click() self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(2) > span" ).click() self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(3) > span" ).click() self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(4) > span" ).click() self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(5) > span" ).click() # self.driver.find_element_by_css_selector( # "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(6) > span").click() # self.driver.find_element_by_css_selector( # "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(7) > span").click() # self.driver.find_element_by_css_selector( # "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(8) > span").click() # self.driver.find_element_by_css_selector( # "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(9) > span").click() # self.driver.find_element_by_css_selector( # "#section-selfchoice > div > div.group-left > ul > li.list.open > div.title-second.open > dl > dt:nth-child(10) > span").click() print("选择了第{}类商标分类!".format(suiji)) zf = self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-right > div > div > h4 > div.header-left > a > span" ).text print(zf) number1 = re.sub(r"\D", "", zf) print(number1) time.sleep(1) self.driver.find_element_by_css_selector( "#section-selfchoice > div > div.group-right > div > div > h4 > div.header-left > a > span" ).click() time.sleep(2) windows = self.driver.window_handles self.driver.switch_to.window(windows[-1]) dl.refresh() time.sleep(1) # self.driver.find_element_by_css_selector("body > div.page > div.search-help > div.tips.tips1 > a").click() # time.sleep(1) # self.driver.find_element_by_css_selector("body > div.page > div.search-help > div.tips.tips2 > a").click() # time.sleep(1) # self.driver.find_element_by_css_selector("body > div.page > div.search-help > div.tips.tips3 > a").click() # time.sleep(1) # self.driver.find_element_by_css_selector("body > div.page > div.search-help > div.tips.tips4 > a").click() # time.sleep(1) number2 = self.driver.find_element_by_css_selector( "#searchList > div.page-content.w-center > div.page-content-left > div.search-top > i" ).text print("权大师为您找到相关结果{}个".format(number2)) self.assertIn(number2, number1) print("检索相似商标数量一致,测试通过!")
def test_number3(self): """智能注册_全类商标跳转测试""" # logging.basicConfig(filename='../LOG/' + __name__ + '.log', # format='[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]', level=logging.DEBUG, # filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p') dl = DengLuPage(self.driver) # 官方推荐有find_element(By.*(""))代替find_element_by_*("") # self.driver.find_element_by_id() # self.driver.find_element() dl.login() time.sleep(2) ActionChains(self.driver).move_to_element( self.driver.find_element_by_css_selector( "body > div.section-banner > div.public-navbar > div > div > h3 > span" )).perform() time.sleep(2) ActionChains(self.driver).move_to_element( self.driver.find_element_by_css_selector( "body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(1) > h3 > a" )).perform() ActionChains(self.driver).release() self.driver.find_element_by_css_selector( "body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(1) > div > dl:nth-child(3) > dd > a:nth-child(3)" ).click() # 获取打开的多个窗口句柄 windows = self.driver.window_handles # 切换到当前最新打开的窗口 self.driver.switch_to.window(windows[-1]) time.sleep(2) self.driver.set_window_size(1920, 1080) self.assertIn("商标智能注册|商标注册查询|商标注册网-权大师", self.driver.title) print(self.driver.title) self.driver.find_element_by_css_selector( "body > div.section-product.width1200 > dl > dd > div.cont-serviceItems > table > tbody > tr > td.td-cont > ul > li:nth-child(3)" ).click() for a in self.driver.find_elements_by_css_selector("#total-price"): print("费用总计:" + a.text) # aa=a.text self.driver.find_element_by_css_selector( "body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow" ).click() time.sleep(2) self.driver.find_element_by_css_selector( "body > div.recommend-help > i").click() # body > div.recommend-help > i # ss = credit_code("en.txt") ss = 'OLAY' self.driver.find_element_by_name("brandName").send_keys( "{}".format(ss)) print("商标名称:{}".format(ss)) self.driver.find_element_by_css_selector( "#create-tuyang > label.label.checked").click() self.driver.find_element_by_css_selector( "body > div.register-wrap.brandinfo-wrap > div.brand-info-wrap.show1.form-wrap > ul > li.brand-upload > div > div.brand-upload-wrap > div.zidongdong-create > ul > li > a" ).click() time.sleep(5) """全类保护""" self.driver.find_element_by_css_selector( "#selectCategoryType > label:nth-child(3)").click() time.sleep(20) print("选择类别:全类保护") xt = self.driver.find_element_by_css_selector( "#first01 > div.category-recommend-first > span.tips > a:nth-child(1)" ).text js = self.driver.find_element_by_css_selector( "#first01 > div.category-recommend-first > span.tips > a:nth-child(2)" ).text print(xt + js) number1 = re.sub(r"\D", "", xt) number2 = re.sub(r"\D", "", js) s2 = int(number1) + int(number2) print(s2) time.sleep(1) self.driver.find_element_by_css_selector( "#first01 > div.category-recommend-first > span.tips").click() time.sleep(2) windows = self.driver.window_handles self.driver.switch_to.window(windows[-1]) dl.refresh() time.sleep(3) # # self.driver.find_element_by_css_selector("body > div.page > div.search-help > div.tips.tips1 > a").click() # time.sleep(1) # self.driver.find_element_by_css_selector("body > div.page > div.search-help > div.tips.tips2 > a").click() # time.sleep(1) # self.driver.find_element_by_css_selector("body > div.page > div.search-help > div.tips.tips3 > a").click() # time.sleep(1) # self.driver.find_element_by_css_selector("body > div.page > div.search-help > div.tips.tips4 > a").click() time.sleep(1) number2 = self.driver.find_element_by_css_selector( "#searchList > div.page-content.w-center > div.page-content-left > div.search-top > i" ).text s3 = int(number2) + 0 print("权大师为您找到相关结果{}个".format(number2)) self.assertEqual(s2, s3, "相似商标数量不一致请及时查看!") print("检索相似商标数量一致,测试通过!")
listings_dict['price'] = price listings_dict['user'] = user listings_dict['status'] = status writer.writerow(listings_dict.values()) #print('Text={}'.format(text)) #print('Rating={}'.format(rating)) # We need to scroll to the bottom of the page because the button is not in the current view yet. #driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") #time.sleep(1) # Locate the next button element on the page and then call `button.click()` to click it. try: button = driver.find_element_by_xpath( '//button[@class="styles__button___3dxOP desktop__button___2Hl0n styles__medium___3KEDn styles__outline___3AGrh desktop__outline___2UF39 styles__loadMore___yYAF4"]' ) #time.sleep(1) actions = ActionChains(driver) actions.move_to_element(button).click().perform() time.sleep(1) except: writer.writerow(listings_dict.values()) except Exception as e: print(e) csv_file.close() driver.close() break
def drag_and_drop(self, source_element, dest_element): ActionChains(self.driver).drag_and_drop(source_element, dest_element).perform()
def goto_admin_configuration_localization(self): # self.browser.find_element(By.ID, 'menu_admin_viewAdminModule') # same as above admin_el = self.browser.find_element(*self.admin) user_man_el = self.browser.find_element(*self.user_management) conf_el = self.browser.find_element(*self.admin_configure) local_el = self.browser.find_element(*self.localization) action = ActionChains(self.browser) action.move_to_element(admin_el) action.pause(0.5) action.move_to_element(user_man_el) action.pause(1) action.move_to_element(conf_el) action.pause(0.25) action.click(local_el) # action.move_to_element(self.wait_for_el(self.admin)) # action.move_to_element(self.wait_for_el(self.user_management)) # action.move_to_element(self.wait_for_el(self.configure)) # action.click(self.wait_for_el(self.localization)) action.perform()
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait # browser = webdriver.Chrome() # # # 隐式等待,下面所有的元素都有等待效果 # browser.implicitly_wait(4) # # # # 显式等待,明确等待某些元素被加载 # wait = WebDriverWait(browser, 4) # # browser.get('https://www.baidu.com') # 动作链,滑动验证 from selenium.webdriver import ActionChains browser = webdriver.Chrome() browser.get( 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') browser.switch_to.frame( 'iframeResult') # 定位切换到里面(swith_to_frame封装为swith_to.frame) one = browser.find_element_by_id('draggable') two = browser.find_element_by_id('droppable') action = ActionChains(browser) # 对browser使用ActionChains的方法 action.drag_and_drop(one, two) # 拖拽某个元素然后分开 action.perform() # 执行链接中所有动作
def move_to_ele_and_click(self, *args, **kwargs): action = ActionChains(self.driver) action.move_to_element(self.find(*args, **kwargs)).click().perform()
def input_expenseAmount(self, text): self.click(*self._expenseAmount) element = self.find_element(*self._expenseAmount) ActionChains(self.driver).send_keys_to_element( element, Keys.BACKSPACE).perform() ActionChains(self.driver).send_keys_to_element(element, text).perform()
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : 鼠标动作链.py # Author: MuNian # Date : 2019-12-03 import time from selenium.webdriver import ActionChains from selenium import webdriver driver = webdriver.Chrome() driver.get('https://www.12306.cn/index/') # 移动 # ac = driver.find_element_by_xpath('//*[@id="toStationText"]') # ActionChains(driver).move_to_element(ac).perform() time.sleep(2) #点击 # ac = driver.find_element_by_xpath('//*[@id="toStationText"]') # ActionChains(driver).move_to_element(ac).click(ac).perform() # time.sleep(2) # ac.send_keys('长沙') # 鼠标右击 ac = driver.find_element_by_xpath('//*[@id="toStationText"]') ActionChains(driver).move_to_element(ac).double_click(ac).perform()
def get_paired_ids(self, shopurl, timeout_secs=45): toret = [] links = [] #try: # self.driver=get_browser() #except TimeoutException: # print(0) # return [] print("Create Driver.... (" + shopurl + ")") #self.driver = webdriver.PhantomJS() #print("...created, get page...("+shopurl+")") #self.driver.get(shopurl) self.driver = get_page(shopurl, 3, timeout_secs) if self.driver is None: print("... unable to get (" + shopurl + ")") return toret print("... got it!(" + shopurl + ")") actcha = ActionChains(self.driver) attempts = 3 while links == [] and attempts > 0: #html = self.driver.page_source #r=req.get(shopurl) #soup = BeautifulSoup(html) #print(html[:200]) #sliders=soup.find_all("div",attrs={"data-reco-type":"CROSS_SELL"}) #sliders = soup.find_all("a", attrs={"class":"productBox"}) #for slide in sliders: # #print(slide['href']) # purl = urlparse(slide['href']) # path = purl.path # lista = path.split(sep="-") # toret.append(lista[-2]+"-"+lista[-1].split(sep=".")[0]) #sliders = soup.find_all("div", attrs={"class":"z-vegas-reco-scroller"}) sliders = self.driver.find_elements_by_class_name( "z-vegas-reco-scroller") if len(sliders) == 2: #sliders[1].send_keys(Keys.ARROW_DOWN) #sliders[1].renderContents() #links = sliders[1].find_all("a") links = sliders[1].find_elements_by_tag_name("a") if len(links) > 0: print(len(links)) for link in links: purl = urlparse(link.get_attribute('href')) lista = purl.path.split(sep="-") #dovrebbero essere sempre lunghi 13 gli id! if len(lista[-2] + "-" + lista[-1].split(sep=".")[0]) < 13: print("Errore in uno degli id trovati!") print(link.get_attribute('href')) print(lista[-2] + "-" + lista[-1].split(sep=".")[0]) else: toret.append((lista[-2] + "-" + lista[-1].split(sep=".")[0]).upper()) else: attempts -= 1 actcha.move_to_element(sliders[1]) actcha.perform() if attempts == 0: print(0) else: print(0) break self.driver.quit() return toret
# coding:utf-8 from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Firefox() driver.get('http://www.baidu.com') mouse = driver.find_element_by_link_text('设置') ActionChains(driver).move_to_element(mouse).perform() driver.find_element_by_link_text('搜索设置').click() # sleep(3) # driver.find_element_by_id('nr').click() sleep(1) driver.find_element_by_xpath('//*[@id="nr"]/option[2]').click() sleep(2) driver.find_element_by_class_name('prefpanelgo').click() sleep(1) driver.find_element_by_class_name('prefpanelgo').click() driver.switch_to.alert.accept() driver.quit()
def login_main(self): # ssl._create_default_https_context = ssl._create_unverified_context driver = self.driver driver.maximize_window() driver.get(self.url) click_keyi_username = driver.find_element_by_xpath( "//div[@class='wp-onb-tit']/a[text()='可疑用户']") self.webdriverwait_click(driver, click_keyi_username) login_button = driver.find_element_by_id('code') self.webdriverwait_click(driver, login_button) time.sleep(1) driver.switch_to.frame( driver.find_element_by_id('tcaptcha_iframe')) # switch 到 滑块frame time.sleep(0.5) bk_block = driver.find_element_by_xpath('//img[@id="slideBg"]') # 大图 web_image_width = bk_block.size web_image_width = web_image_width['width'] bk_block_x = bk_block.location['x'] slide_block = driver.find_element_by_xpath( '//img[@id="slideBlock"]') # 小滑块 slide_block_x = slide_block.location['x'] bk_block = driver.find_element_by_xpath( '//img[@id="slideBg"]').get_attribute('src') # 大图 url slide_block = driver.find_element_by_xpath( '//img[@id="slideBlock"]').get_attribute('src') # 小滑块 图片url slid_ing = driver.find_element_by_xpath( '//div[@id="tcaptcha_drag_thumb"]') # 滑块 os.makedirs('./image/', exist_ok=True) self.urllib_download(bk_block, './image/bkBlock.png') self.urllib_download(slide_block, './image/slideBlock.png') time.sleep(0.5) img_bkblock = Image.open('./image/bkBlock.png') real_width = img_bkblock.size[0] width_scale = float(real_width) / float(web_image_width) position = self.get_postion('./image/bkBlock.png', './image/slideBlock.png') real_position = position[1] / width_scale real_position = real_position - (slide_block_x - bk_block_x) track_list = self.get_track(real_position + 4) ActionChains(driver).click_and_hold( on_element=slid_ing).perform() # 点击鼠标左键,按住不放 time.sleep(0.2) # print('第二步,拖动元素') for track in track_list: ActionChains(driver).move_by_offset( xoffset=track, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y) time.sleep(0.002) # ActionChains(driver).move_by_offset(xoffset=-random.randint(0, 1), yoffset=0).perform() # 微调,根据实际情况微调 time.sleep(1) # print('第三步,释放鼠标') ActionChains(driver).release(on_element=slid_ing).perform() time.sleep(2) try: driver.find_element_by_id('tcaptcha_iframe') print("没成功,继续来一次") except: self.login_main() print('登录成功') self.after_quit()
#select list bar driver.find_element_by_xpath("//div//div//div[1]//div[2]//select[1]").click() #select wednesday driver.find_element_by_xpath("//option[contains(text(),'Wednesday')]").click() SelectedDay = driver.find_element_by_xpath( "//p[contains(text(),'Day selected :- Wednesday')]").text assert "Wednesday" in SelectedDay California = driver.find_element_by_xpath( "//option[contains(text(),'California')]") Florida = driver.find_element_by_xpath("//option[contains(text(),'Florida')]") Washington = driver.find_element_by_xpath( "//option[contains(text(),'Washington')]") time.sleep(3) ActionChains(driver).key_down(Keys.CONTROL).click(California).key_up( Keys.CONTROL).perform() time.sleep(2) ActionChains(driver).key_down(Keys.CONTROL).click(Florida).key_up( Keys.CONTROL).perform() time.sleep(2) ActionChains(driver).key_down(Keys.CONTROL).click(Washington).key_up( Keys.CONTROL).perform() time.sleep(2) #get all selected button driver.find_element_by_xpath( "//button[contains(text(),'Get All Selected')]").click() time.sleep(1) SelectedCities = driver.find_element_by_xpath( "//p[contains(text(),'Options selected are : Florida,Washingt')]").text assert "Florida,Wash" in SelectedCities
class AccountCreation(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.set_window_size(height=1920, width=1080) self.driver.maximize_window() self.mail = '*****@*****.**' self.parola = 'Dan1231231' self.wait = WebDriverWait(self.driver, 10) self.url = ('https://www.emag.ro/homepage') abc = ["abcdefghijklmnopqrstuvwxyz1234567890"] for i in abc: self.mail = random.choice(i) + random.choice(i) + random.choice( i) + random.choice(i) + "@gmail.com" self.prenume = "Dany" self.nume = "Moceanu" self.parola = "D@31231" self.telefon = "+40721121456" self.action = ActionChains(self.driver) def testCreateAccount(self): self.driver.get(self.url) self.assertIn("eMAG.ro - Libertate în fiecare zi", self.driver.title, "Am ajuns pe homepage") self.wait.until( EC.visibility_of_element_located( (By.XPATH, "/html/body/div[3]/nav[1]/div/div/div[3]/div/div[2]/a/span" ))).click() # Login / Create account page self.assertIn("https://www.emag.ro/user/login", self.driver.current_url, "Am ajuns pe pagina de login/create account") self.wait.until( EC.visibility_of_element_located( (By.XPATH, "//*[@id='email']"))).send_keys(self.mail) self.wait.until( EC.visibility_of_element_located( (By.XPATH, "/html/body/form/div[4]/div/button"))).click() self.assertIn("https://www.emag.ro/user/register/", self.driver.current_url, "Register account") self.wait.until( EC.visibility_of_element_located( (By.XPATH, "//*[@id='r_name']"))).send_keys(self.prenume + ' ' + self.nume) self.wait.until( EC.visibility_of_element_located( (By.XPATH, '//*[@id="r_password"]'))).send_keys(self.parola) self.wait.until( EC.visibility_of_element_located( (By.XPATH, '//*[@id="r_password_confirmation"]'))).send_keys(self.parola) # terms = self.wait.until(EC.visibility_of_element_located((By.XPATH, '/html/body/form/div[5]/div/label'))) # print(terms) time.sleep(1) term = self.driver.find_element_by_xpath('//*[@id="agree_terms"]') self.action.move_by_offset(xoffset=609, yoffset=545).click().perform() self.wait.until( EC.visibility_of_element_located( (By.XPATH, '/html/body/form/div[7]/div/button'))).click() def tearDown(self): self.driver.quit()
def enter(self): action = ActionChains(self.driver) action.send_keys(Keys.CONTROL).send_keys(Keys.ENTER).perform()
from selenium import webdriver from selenium.webdriver import ActionChains import time driver = webdriver.Chrome(executable_path=r"C:\dchrome\chromedriver.exe") driver.get("https://google.com") time.sleep(3) elem = driver.find_element_by_link_text("Privacidad") hover = ActionChains(driver).move_to_element(elem) hover.perform()
def test_candidate_classifications_filtering( driver, user, public_candidate, public_filter, public_group, upload_data_token, taxonomy_token, classification_token, ): # Post an object with a classification candidate_id = str(uuid.uuid4()) status, data = api( "POST", "candidates", data={ "id": candidate_id, "ra": 234.22, "dec": -22.33, "redshift": 3, "transient": False, "ra_dis": 2.3, "filter_ids": [public_filter.id], "passed_at": str(datetime.datetime.utcnow()), }, token=upload_data_token, ) assert status == 200 status, data = api( "POST", "sources", data={"id": candidate_id}, token=upload_data_token, ) assert status == 200 status, data = api( 'POST', 'taxonomy', data={ 'name': "test taxonomy" + str(uuid.uuid4()), 'hierarchy': taxonomy, 'group_ids': [public_group.id], 'provenance': f"tdtax_{__version__}", 'version': __version__, 'isLatest': True, }, token=taxonomy_token, ) assert status == 200 taxonomy_id = data['data']['taxonomy_id'] status, data = api( 'POST', 'classification', data={ 'obj_id': candidate_id, 'classification': 'Algol', 'taxonomy_id': taxonomy_id, 'probability': 1.0, 'group_ids': [public_group.id], }, token=classification_token, ) assert status == 200 driver.get(f"/become_user/{user.id}") driver.get("/candidates") driver.click_xpath( f'//*[@data-testid="filteringFormGroupCheckbox-{public_group.id}"]', wait_clickable=False, ) driver.click_xpath("//div[@id='classifications-select']") driver.click_xpath("//li[@data-value='Algol']", scroll_parent=True) # Click somewhere outside to remove focus from classification select header = driver.wait_for_xpath("//header") ActionChains(driver).move_to_element(header).click().perform() driver.click_xpath('//button[text()="Search"]') # Should see the posted classification driver.wait_for_xpath(f'//a[@data-testid="{candidate_id}"]') # Now search for a different classification driver.click_xpath("//div[@id='classifications-select']") # Clear old classification selection driver.click_xpath("//li[@data-value='Algol']", scroll_parent=True) driver.click_xpath("//li[@data-value='AGN']", scroll_parent=True) # Click somewhere outside to remove focus from classification select header = driver.wait_for_xpath("//header") ActionChains(driver).move_to_element(header).click().perform() driver.click_xpath('//button[text()="Search"]') # Should no longer see the classification driver.wait_for_xpath_to_disappear(f'//a[@data-testid="{candidate_id}"]')
def step_impl(context): time.sleep(1) a = context.browser.find_element(*SignUpLocator.SIGNUP) actions = ActionChains(context.browser) actions.move_to_element(a).click().perform() time.sleep(2)
def get_samsung(self): action = ActionChains(self.drive) samsung = self.drive.find_element_by_xpath(self.samsung) action.move_to_element(samsung).perform() return action.move_to_element(samsung).click().perform()
# # 滑轨元素 # ac_guide = driver.find_element_by_xpath('//div[@class="gt_guide_tip gt_show"]') # # 滑块滑轨底层元素 # ac_curtain = driver.find_element_by_xpath('//div[@class="gt_curtain_tip gt_hide"]') # 小锁元素 # ac_ajax = driver.find_element_by_xpath('//div[@class="gt_ajax_tip gt_ready"]') # print ac_slider.location # print ac_guide.location # print ac_curtain.location # print ac_ajax.location print 'Find all.********************' break except: time.sleep(1) print 'Not find slider.' dr1 = ActionChains(driver) dr1.move_to_element(ac_slider).pause(0.5).perform() time.sleep(1.1) driver.save_screenshot('1.png') # move_by_offset是基于当前元素坐标的位移 dr1.click_and_hold(ac_slider).move_by_offset(198, 0).pause(0.2).perform() # dr1.reset_actions()方法很重要——重置操作 time.sleep(0.5) file_name = '2.png' driver.save_screenshot(file_name) im = Image.open(file_name) im2 = Image.open('1.png') box = (562, 224, 822, 340) region = im.crop(box) region2 = im2.crop(box) im_cut1 = 'cut1.png'
class BasePage: _driver: WebDriver _params = {} _error_max = 10 _error_count = 0 _black_list = [] _retry_max = 3 _retry = 0 def __init__(self, driver: WebDriver = None): browser = os.getenv("browser").lower() if driver is None: logging.info("开始初始化web driver") if browser == "headless": self._driver = webdriver.PhantomJS( executable_path=phantom_js_path) elif browser == "firefox": self._driver = webdriver.Firefox( executable_path=geckodriver_path) else: options = webdriver.ChromeOptions() options.debugger_address = "127.0.0.1:9222" self._driver = webdriver.Chrome( executable_path=chromedriver_path) self._driver.implicitly_wait(2) logging.info("web driver初始化完成,测试使用浏览器为:{}".format(browser)) else: self._driver = driver self.action = ActionChains(self._driver) # 测试步骤驱动 def steps(self, path): with open(path) as f: steps: list[dict] = yaml.safe_load(f) element: WebElement = None for step in steps: logging.info(step) if "by" in step.keys(): element = self.find(step["by"], step["value"]) if "action" in step.keys(): action = step["action"] if action == "find": pass elif action == "click": element.click() elif action == "text": element.text() elif action == "attribute": element.get_attribute(step["value"]) elif action in ["send", "input"]: content: str = step["value"] for key in self._params.keys(): content = content.replace("{%s}" % key, self._params[key]) element.send_keys(content) def find(self, by, value: str = None): """ 定位单个元素 :param by: :param value: :return: """ logging.info("定位元素({},{})".format(by, value)) try: element = self._driver.find_element(*by) \ if isinstance(by, tuple) else self._driver.find_element(by, value) self._error_count = 0 return element except Exception as e: if self._error_count > self._error_max: raise e self._error_count += 1 for element in self._black_list: logging.info(element) elements = self._driver.find_elements(*element) if len(elements) > 0: elements[0].click() return self.find(by, value) logging.error("black list no one found") raise e def finds(self, value, by=By.CSS_SELECTOR): """ 定位多个元素 :param by: :param value: :return: """ return self._driver.find_elements(by, value) def wait(self, value, by=By.CSS_SELECTOR, timeout=5): element = self.find(by, value) WebDriverWait(self._driver, timeout).until(EC.presence_of_element_located(element)) def send_keys(self, value, text, by=By.CSS_SELECTOR): """ 输入文本 :param value: :param text: :param by: :return: """ element = self.find(by, value) element.clear() element.send_keys(text) logging.info("输入文本:{}".format(text)) def click(self, value, by=By.CSS_SELECTOR): """ 点击元素 :param value: :param by: :return: """ self.find(by, value).click() logging.info("点击元素:({},{})".format(by, value)) def clear(self, value, by=By.CSS_SELECTOR): """ 清除内容 :param value: :param by: :return: """ self.find(by, value).clear() def close(self): """ 关闭标签页 :return: """ sleep(3) self._driver.close() logging.info("关闭标签页") def quit(self): """ 关闭浏览器 :return: """ sleep(3) self._driver.quit() logging.info("关闭浏览器") def open(self, url): """ 打开浏览器 :param url: :return: """ self._driver.get(url) logging.info("打开测试目标网页:{}".format(url)) def get_attribute(self, name, value, by=By.CSS_SELECTOR): """ 获取元素属性 :param method: :param value: :param by: :return: """ self.find(by, value).get_attribute(name) logging.info('获取元素"{}"属性'.format(name)) def get_location_and_size(self, value, by=By.CSS_SELECTOR): """ 获取元素坐标 :param value: :param by: :return: """ location = self.find(by, value).location size = self.find(by, value).size print("location:{}\nsize:{}".format(location, size)) return location, size def get_page_source(self): """ 获取网页源代码 :return: """ logging.info("获取网页源代码") return self._driver.page_source def refresh(self): """ 刷新页面 :return: """ self._driver.refresh() logging.info("刷新网页") def set_window_size(self, width, height): """ 设置窗口大小 :param width: :param height: :return: """ self._driver.set_window_size(width, height) def minimize_window(self): """ 最小化窗口 :return: """ self._driver.minimize_window() logging.info("最小化窗口") def maximize_window(self): """ 最大化窗口 :return: """ self._driver.maximize_window() logging.info("最大化窗口") def click_and_hold(self, value, by=By.CSS_SELECTOR): on_element = (by, value) self.action.click_and_hold(on_element).perform() def context_click(self, value, by=By.CSS_SELECTOR): on_element = (by, value) self.action.context_click(on_element).perform() def double_click(self, value, by=By.CSS_SELECTOR): pass def drag_and_drop(self, source, target): pass def drag_and_drop_by_offset(self, source, xoffset, yoffset): pass def key_down(self, key_name, value, by=By.CSS_SELECTOR): pass def move_by_offset(self, xoffset, yoffset): pass def move_to_element(self, value, by=By.CSS_SELECTOR): pass def move_to_element_with_offset(self, value, xoffset, yoffset, by=By.CSS_SELECTOR): pass def release(self, value, by=By.CSS_SELECTOR): pass def switch_to_frame(self, value): self._driver.switch_to.frame(value) def switch_to_default_content(self): self._driver.switch_to.default_content() def switch_to_parent_frame(self): self._driver.switch_to.parent_frame() def get_window_handles(self): handles = self._driver.window_handles return handles def switch_to_window(self, window_name): self._driver.switch_to.window(window_name) def execute_script(self, script, *args): self._driver.execute_script(script, *args) def switch_to_alert(self): return self._driver.switch_to.alert def switch_to(self): return self._driver.switch_to
password.send_keys(Keys.RETURN) # Get to map project = findElement(r'//*[@id="projectList"]/table/tbody/tr/td[1]/a') project.click() mapDrop = findElement(r'//*[@id="menu"]/ul/li[7]/span/a') mapDrop.click() projmap = findElement(r'//*[@id="menu"]/ul/li[7]/div[1]/div/a[1]') projmap.click() driver.switch_to.window(driver.window_handles[1]) closeIntro = findElement(r'/html/body/div[7]/div[1]/button/span[1]') time.sleep(2) closeIntro.click() actionChains = ActionChains(driver) fullmap = findElement(r'//*[@id="container"]') actionChains.context_click(fullmap).perform() analytics = findElement(r'//*[@id="piemenuCanvas"]') action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(analytics, 150, 200).perform() action.click() action.perform() owner = findElement(r'//*[@id="geoanalytical-ownership-by-owner"]/span') owner.click() time.sleep(1) # Get session ID to be able to click target = findElement(r'//*[@id="analytic-criteria-form"]/div/table/tbody/tr[4]/td[2]/div/a')
def send_messenger(target_fd_id, msg): driver.get("https://www.messenger.com/t/" + target_fd_id) ActionChains(driver).send_keys(msg).send_keys(Keys.ENTER).perform() print("done sending")
# Create New Gist driver.get("https://github.com/") driver.find_element_by_xpath('//summary[@aria-label="Create new…"]').click() driver.find_element_by_xpath( '//a[@data-ga-click="Header, create new gist"]').click() driver.find_element_by_name('gist[description]').send_keys('Gist ' + str(datetime.now())) driver.find_element( By.NAME, "gist[contents][][name]").send_keys("file" + str(datetime.now()) + ".md") el = driver.find_element(By.CLASS_NAME, "CodeMirror-lines") ActionChains(driver).move_to_element(el).click(el).send_keys( 'Description file' + str(datetime.now())).perform() driver.find_element_by_name('gist[public]').click() # Edit Existing Gist driver.get("https://github.com/") driver.find_element_by_xpath( '//summary[@aria-label="View profile and more"]').click() driver.find_element_by_xpath( '//a[@data-ga-click="Header, your gists, text:your gists"]').click() driver.find_element_by_xpath( '//*[@id="gist-pjax-container"]//div[2]/div[1]//a[2]/strong').click() driver.find_element_by_xpath('//a[@aria-label="Edit this Gist"]').click()