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 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 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 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 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 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 delete_file(self, filename): """ Delete `filename`. """ self('files_tab').click() element = self.find_file(filename) chain = ActionChains(self.browser) chain.context_click(element).perform() time.sleep(0.5) self('file_delete').click() time.sleep(0.5)
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 rename_file(self, old, new): """ Rename `old` to `new`. """ self('files_tab').click() element = self.find_file(old) chain = ActionChains(self.browser) chain.context_click(element).perform() self('file_rename').click() prompt = ValuePrompt(self.browser, self.port) prompt.set_value(new)
def view_file(self, filename): """ View image `filename` in another window via context menu. """ self('files_tab').click() element = self.find_file(filename) chain = ActionChains(self.browser) chain.context_click(element).perform() self('file_view').click() self.browser.switch_to_window(self.browser.window_handles[-1]) return BasePageObject.verify(self.browser, self.port)
def output_edit_driver(self, driver_pathname): """ Return :class:`DriverPage` associated with the output port. """ # FIXME: can't get response from context click. chain = ActionChains(self.browser) chain.context_click(self.output_port).perform() time.sleep(0.5) self('edit_driver').click() editor_id = 'ObjectFrame_%s' % driver_pathname.replace('.', '-') return DriverPage(self.browser, self.port, (By.ID, editor_id))
def _context_click(self, name): """ Display context menu. """ chain = ActionChains(self.browser) # Default is centered which causes problems in some contexts. # Offset is apparently limited, (20, 20) had problems. chain.move_to_element_with_offset(self.root, 15, 15) chain.context_click(None) chain.perform() time.sleep(0.5) self(name).click()
def toggle_files(self, filename): """ Toggle files display, using context menu of `filename`. """ self("files_tab").click() time.sleep(0.5) element = self.find_file(filename) chain = ActionChains(self.browser) chain.context_click(element).perform() time.sleep(0.5) self("file_toggle").click() time.sleep(0.5)
def test_example(driver): # Always include driver as a function parameter. # This is the selenium webdriver that will allow # you to interact with the webpage. tt.reset_page(driver) # Most testing_tools functions require driver as an input. # Presses the reset button to start the page fresh. # Usually useful but not always needed. # More documentation on testing_tools can be found # in nengo_gui/testing_tools.py time.sleep(1) # Waits a small amount of time to ensure the page has # time to reset. tt.update_editor(driver,''' import nengo model = nengo.Network() with model: stim = nengo.Node([0]) a = nengo.Ensemble(n_neurons=50, dimensions=1) nengo.Connection(stim, a) ''') # The page will now load this code into the code editor stim = driver.find_element_by_xpath('//*[@class="node"]') a = driver.find_element_by_xpath('//*[@class="ens"]') # Finds the 'stim' and 'a' nodes and saves them as a webElements. action = ActionChains(driver) # ActionChains allow you to link together multiple mouse events # then execute them in that order. action.move_to_element(stim); action.context_click() action.perform() time.sleep(1) # The stim element has now been right clicked. # WARNING: when using ActionChains reinitialize ActionChains # after every .perform() call, it is not clear why but # ActionChains does not seem to reset properly after this call. right_click_menu = driver.find_element_by_xpath('//*[@class="dropdown-menu"]') assert(bool(stim) and bool(a) == True) # Tests if both elements are present. assert(bool(right_click_menu) == True) # Tests if stim has been properly clicked if('TRAVIS' in os.environ): ########## TRAVIS ONLY tt.imgur_screenshot(driver)
def view_library_item_docs(self, item_name): chain = ActionChains(self.browser) current_windows = set(self.browser.window_handles) self.show_library() item = self.get_library_item(item_name) chain.context_click(item).perform() self("library_item_docs").click() new_windows = set(self.browser.window_handles) - current_windows docs_window = list(new_windows)[0] return docs_window
def test_window_handling(self): element = self.driver.find_element(*HomeLoc.SALE_SECTION) actionChain = ActionChains(self.driver) print ('now down at action chain') actionChain.context_click(element).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform() windowhandels = self.driver.window_handles time.sleep(2) self.driver.switch_to_window(windowhandels[1]) title = self.driver.title print (title) assert "Official Jabong Coupons, Online Sale Offers, Discount Deals" in self.driver.title print ('assert is passed')
def _context_click(self, name): """ Display context menu. """ chain = ActionChains(self.browser) # Just using center of self.root had an isolated 'overlap' failure. chain.move_to_element_with_offset(self('data').element, 2, 2) chain.context_click(None) chain.perform() time.sleep(0.5) # Wait for menu to display. text = self(name).text self(name).click() time.sleep(0.5) # Wait to pop-down. return text
def delete_file(self, filename, confirm=True): """ Delete `filename`. """ self('files_tab').click() element = self.find_file(filename) chain = ActionChains(self.browser) chain.context_click(element).perform() time.sleep(0.5) self('file_delete').click() time.sleep(0.5) page = ConfirmationPage(self) if confirm: page.click_ok() else: page.click_cancel()
def test_data_to_csv(driver): tt.reset_page(driver) tt.update_editor(driver,''' import nengo model = nengo.Network() with model: stim = nengo.Node([0]) a = nengo.Ensemble(n_neurons=50, dimensions=1) nengo.Connection(stim, a) ''') time.sleep(1) actions = ActionChains(driver) elements = ['node','ens'] for elem in elements: for x in range(2): node = driver.find_element_by_xpath('//*[@class="'+elem+'"]') actions = ActionChains(driver) actions.move_to_element(node) actions.context_click() actions.perform() time.sleep(1) actions = ActionChains(driver) menu = driver.find_element_by_xpath('//*[@class="dropdown-menu"]/li['+str(x+1)+']') actions.move_to_element(menu) actions.click() actions.perform() time.sleep(0.5) driver.execute_script("""a = function(){var data_set = Nengo.Component.components data_set.forEach(function(data,index){ if(data.constructor === Nengo.Value){ data.data_store.reset(); data.data_store.push([1,10+index]); }; }); return data_to_csv(data_set)};""") time.sleep(1) result = driver.execute_script("return a()") print result test_data = '''Graph Name,stim,a Times,Dimension1,Dimension1 1,11,12''' assert result == test_data
def add_file_to_folder(self, folder_path, file_path): """ Read in `file_path` """ if file_path.endswith('.pyc'): file_path = file_path[:-1] self('files_tab').click() element = self.find_file(folder_path) chain = ActionChains(self.browser) chain.context_click(element).perform() time.sleep(0.5) self('file_add').click() time.sleep(0.5) self.file_chooser = file_path time.sleep(1) # Some extra time for the file tree update.
def test_remove_success(self): table = self.driver.find_element_by_id('dataTable') self.create_units(table) tr = table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(3) + ')') actions = ActionChains(self.driver) actions.move_to_element(tr.find_element_by_css_selector('td:nth-child(2)')) actions.click() actions.key_down(Keys.SHIFT) actions.move_to_element(table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(5) + ') td:nth-child(3)')) actions.click() actions.key_up(Keys.SHIFT) actions.move_to_element(table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(4) + ') td:nth-child(3)')) actions.context_click().send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN) actions.send_keys(Keys.RETURN) actions.perform() self.assertEqual(len(self.driver.find_elements_by_css_selector('.htCore tbody tr')), 3 * 2)
def show_workflow(self, component_name): """ Show workflow of `component_name`. """ self("objects_tab").click() xpath = "//div[@id='otree_pane']//li[(@path='%s')]//a" % component_name element = WebDriverWait(self.browser, TMO).until(lambda browser: browser.find_element_by_xpath(xpath)) element.click() time.sleep(0.5) # Try to recover from context menu not getting displayed. for retry in range(3): chain = ActionChains(self.browser) chain.context_click(element).perform() try: self("obj_workflow").click() break except TimeoutException: if retry >= 2: raise
def edit_file(self, filename, dclick=True): """ Edit `filename` via double-click or context menu. """ xpath = "//a[(@path='/%s')]" % filename element = WebDriverWait(self.browser, TMO).until(lambda browser: browser.find_element_by_xpath(xpath)) chain = ActionChains(self.browser) for i in range(10): try: if dclick: chain.double_click(element).perform() else: chain.context_click(element).perform() self("file_edit").click() except StaleElementReferenceException: logging.warning("edit_file: StaleElementReferenceException") element = WebDriverWait(self.browser, 1).until(lambda browser: browser.find_element_by_xpath(xpath)) chain = ActionChains(self.browser) else: break
def view_geometry(self, filename, dclick=True): """ View geometry `filename` via double-click or context menu. """ self('files_tab').click() element = self.find_file(filename) chain = ActionChains(self.browser) if dclick: # This has had issues... for i in range(10): try: chain.double_click(element).perform() except StaleElementReferenceException: logging.warning('edit_file: StaleElementReferenceException') element = self.find_file(filename, 1) chain = ActionChains(self.browser) else: break else: chain.context_click(element).perform() self('file_geometry').click() self.browser.switch_to_window(self.browser.window_handles[-1]) return GeometryPage.verify(self.browser, self.port)
def edit_file(self, filename, dclick=True): """ Edit `filename` via double-click or context menu. """ self("files_tab").click() element = self.find_file(filename) chain = ActionChains(self.browser) if dclick: # This has had issues... for i in range(10): try: chain.double_click(element).perform() except StaleElementReferenceException: logging.warning("edit_file: StaleElementReferenceException") element = self.find_file(filename, 1) chain = ActionChains(self.browser) else: break else: chain.context_click(element).perform() self("file_edit").click() self.browser.switch_to_window("Code Editor") return EditorPage.verify(self.browser, self.port)
def test_remove_permission(self): table = self.driver.find_element_by_id('dataTable') self.create_units(table) self.driver.authorize(username=self.guest.email, password='******') self.driver.open_url(reverse('units:list', kwargs={'lab_pk': unicode(self.lab.pk)})) table = self.driver.find_element_by_id('dataTable') tr = table.find_element_by_css_selector('.htCore tbody tr:nth-child(1)') actions = ActionChains(self.driver) actions.move_to_element(tr.find_element_by_css_selector('td:nth-child(2)')) actions.click() actions.key_down(Keys.SHIFT) actions.move_to_element(table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(5) + ') td:nth-child(3)')) actions.click() actions.key_up(Keys.SHIFT) actions.move_to_element(table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(4) + ') td:nth-child(3)')) actions.context_click().send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN) actions.send_keys(Keys.RETURN) actions.perform() self.assertTrue(self.driver.is_element_present('.alert-danger')) self.assertEqual(self.driver.find_element_by_css_selector('.messages').text, 'PERMISSION DENIED')
def toggle_files(self, filename=None): """ Toggle display of hidden files. Use context menu of `filename` if provided, otherwise use the context menu of the file tree pane. """ self('files_tab').click() time.sleep(0.5) if filename: element = self.find_file(filename) chain = ActionChains(self.browser) chain.context_click(element).perform() time.sleep(0.5) self('file_toggle').click() time.sleep(0.5) else: element = self.browser.find_element(By.ID, 'ftree_pane') chain = ActionChains(self.browser) chain.context_click(element).perform() time.sleep(0.5) self('ftree_toggle_files_button').click() time.sleep(0.5)
def download_book(url, name): chromedriver = '/home/rajdeep1008/Desktop/chromedriver' os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get(url) link = driver.find_element_by_link_text(name) actionChains = ActionChains(driver) actionChains.context_click(link) actionChains.send_keys(Keys.ARROW_DOWN) actionChains.send_keys(Keys.ARROW_DOWN) actionChains.send_keys(Keys.ARROW_DOWN) actionChains.send_keys(Keys.ARROW_DOWN) actionChains.send_keys(Keys.RETURN) actionChains.perform() while True: if not os.path.isfile('/home/rajdeep1008/Downloads/' + name + '.pdf'): time.sleep(5) else: break driver.quit()
from pytesser import * from PIL import Image from PIL import ImageEnhance from selenium import webdriver from selenium.webdriver import ActionChains import sys image = Image.open('B.jpg') # Open image object using PIL print image_to_string(image) # Run tesseract.exe on image driver = webdriver.Chrome() driver.get("http://jwxt.swpu.edu.cn/logout.do") username ='******' password = '******' va = '/html/body/table/tbody/tr/td/table[3]/tbody/tr/td[2]/form/table/tbody/tr[2]/td/table/tbody/tr[3]/td[2]/input' image = '//*[@id="vchart"]' action = ActionChains(driver) imagesave = driver.find_element_by_xpath(image) action.context_click(imagesave).perform()
def get_gender_sp_race(out, driver, cat, now, raw_name): # Gender # Right Click chart_div = driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[35]/transform/div/div[3]/div' ) driver.execute_script("arguments[0].scrollIntoView();", chart_div) actionChains = ActionChains(driver) actionChains.context_click(chart_div).pause(3).send_keys( Keys.ENTER).perform() time.sleep(2) cat_div = driver.find_elements_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[35]/transform/div/div[3]/div/detail-visual-modern/div/visual-modern/div/div/div[2]/div[1]/div[3]/div/*' ) val_div = driver.find_elements_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[35]/transform/div/div[3]/div/detail-visual-modern/div/visual-modern/div/div/div[2]/div[1]/div[4]/div/div/div/*' ) expected_cats = ["Female", "Male"] for ct, val in zip(cat_div, val_div): if ct.text not in expected_cats: raise Exception("Unexpected Gender: " + ct.text) out[cat + ": " + ct.text] = val.text # Raw driver.save_screenshot(raw_name + "/gender_" + cat + "_" + now + ".png") driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[35]/transform/div/div[3]/visual-container-pop-out-bar/div/div[1]/button' ).click() time.sleep(2) # Spreadtype # Right Click chart_div = driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[33]/transform/div/div[3]/div' ) driver.execute_script("arguments[0].scrollIntoView();", chart_div) actionChains = ActionChains(driver) actionChains.context_click(chart_div).pause(3).send_keys( Keys.ENTER).perform() time.sleep(2) cat_div = driver.find_elements_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[33]/transform/div/div[3]/div/detail-visual-modern/div/visual-modern/div/div/div[2]/div[1]/div[3]/div/*' ) val_div = driver.find_elements_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[33]/transform/div/div[3]/div/detail-visual-modern/div/visual-modern/div/div/div[2]/div[1]/div[4]/div/div/div/*' ) expected_cats = [ "Community", "Close Contact", "Unknown", "Household Contact", "Travel", "Under Investigation" ] for ct, val in zip(cat_div, val_div): if ct.text not in expected_cats: raise Exception("Unexpected Spread Type: " + ct.text) out[cat + " Spread Type: " + ct.text] = val.text # Raw driver.save_screenshot(raw_name + "/spread_" + cat + "_" + now + ".png") driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[33]/transform/div/div[3]/visual-container-pop-out-bar/div/div[1]/button' ).click() time.sleep(2) # Race # Right Click chart_div = driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[68]/transform/div/div[3]/div/visual-modern/div' ) driver.execute_script("arguments[0].scrollIntoView();", chart_div) actionChains = ActionChains(driver) actionChains.context_click(chart_div).pause(3).send_keys( Keys.ENTER).perform() time.sleep(2) cat_div = driver.find_elements_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[68]/transform/div/div[3]/div/detail-visual-modern/div/visual-modern/div/div/div[2]/div[1]/div[3]/div/*' ) val_div = driver.find_elements_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[68]/transform/div/div[3]/div/detail-visual-modern/div/visual-modern/div/div/div[2]/div[1]/div[4]/div/div/div/*' ) expected_cats = [ "White", "Unknown", "American Indian", "2 or More", "Asian", "Other", "Black" ] for ct, val in zip(cat_div, val_div): if ct.text not in expected_cats: raise Exception("Unexpected Race: " + ct.text) out[cat + " Race: " + ct.text] = val.text # Raw driver.save_screenshot(raw_name + "/race_" + cat + "_" + now + ".png") driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[68]/transform/div/div[3]/visual-container-pop-out-bar/div/div[1]/button' ).click() time.sleep(2) return out
# coding=utf-8 import time from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.maximize_window() driver.get('https://www.baidu.com') time.sleep(2) # ActionChains下相关方法在当前的firefox不工作 element = driver.find_element_by_xpath("//*[@id='lg']/img") actionChains = ActionChains(driver) actionChains.context_click(element).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform() # actionChains.context_click(element).send_keys('i').perform()
def right_click(element): utils.log_debug('right_click') if type(element) in (tuple, list): element = element[0] actions = ActionChains(driver()) actions.context_click(element).perform()
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')) #执行 action.perform() time.sleep(3) driver.quit()
class TestActionChains(): def setup(self): self.driver = webdriver.Chrome() self.action = ActionChains(self.driver) self.driver.maximize_window() self.driver.implicitly_wait(5) def teardown(self): self.driver.quit() @pytest.mark.skip # 忽略这个用例 def test_case_click(self): self.driver.get('http://sahitest.com/demo/clicks.htm') ele_click = self.driver.find_element_by_xpath( '//input[@value="click me"]') ele_double = self.driver.find_element_by_xpath( '//input[@value="dbl click me"]') ele_right = self.driver.find_element_by_xpath( '//input[@value="right click me"]') self.action.click(ele_click) self.action.context_click(ele_right) # 右键点击 self.action.double_click(ele_double) sleep(3) self.action.perform() # 执行以上动作 sleep(3) @pytest.mark.skip def test_move_to(self): self.driver.get('http://www.baidu.com') ele = self.driver.find_element_by_id('s-usersetting-top') # 百度首页的设置 self.action.move_to_element(ele) self.action.perform() @pytest.mark.skip def test_dragdrop(self): self.driver.get('http://sahitest.com/demo/dragDropMooTools.htm') drag_ele = self.driver.find_element_by_id('dragger') drop1_ele = self.driver.find_element_by_xpath( '//*[@class="item"][1]') # 第一个放置框 drop2_ele = self.driver.find_element_by_xpath( '//*[@class="item"][2]') # 第二个放置框 drop3_ele = self.driver.find_element_by_xpath( '//*[@class="item"][3]') # 第三个放置框 drop4_ele = self.driver.find_element_by_xpath( '//*[@class="item"][4]') # 第四个放置框 # 方法一 self.action.drag_and_drop(drag_ele, drop1_ele).perform() # 将第一个元素拖拽到第二个元素 # 方法二 self.action.click_and_hold(drag_ele).release( drop2_ele).perform() # 先按住,再释放 # 方法三 self.action.click_and_hold(drag_ele).move_to_element( drop3_ele).release().perform() sleep(3) def test_keys(self): self.driver.get('http://sahitest.com/demo/label.htm') ele = self.driver.find_element_by_xpath('//input[@type="textbox"][1]') ele.click() self.action.send_keys('username').pause(1) # 输入username并暂停一秒 self.action.send_keys(Keys.SPACE).pause(1) # 输入空格并暂停一秒 self.action.send_keys('tom').pause(1) self.action.send_keys(Keys.BACK_SPACE).perform() # 删除输入的内容 sleep(3)
from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Firefox( executable_path= "/home/pranay/Drivers/geckodriver-v0.24.0-linux64/geckodriver") driver.get("http://swisnl.github.io/jQuery-contextMenu/demo.html") button = driver.find_element_by_xpath( "/html/body/div/section/div/div/div/p/span") actions = ActionChains(driver) actions.context_click(button).perform()
from selenium import webdriver from selenium.webdriver import ActionChains import time driver = webdriver.Chrome( executable_path= "C:/Users/user/PycharmProjects/selenium_python/driver/chromedriver.exe") driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html") driver.maximize_window() click_me = driver.find_element_by_xpath( "/html/body/div/section/div/div/div/p/span") actions = ActionChains(driver) actions.context_click(click_me).perform()
def main(): driver = webdriver.Chrome() homeurl = r'https://www.autoitscript.com' try: driver.get(homeurl) link1 = driver.find_element_by_xpath("//*[@id='menu-item-207']") link2 = driver.find_element_by_xpath("//*[@id='menu-item-209']/a") actions = ActionChains(driver) actions.move_to_element(link1) actions.click(link2) actions.perform() # link2.click() time.sleep(10) # roll and click for download link3 = driver.find_element_by_xpath( ".//*[@id='post-77']/div/table[2]/tbody/tr[1]/td[2]/a/img") driver.execute_script("arguments[0].scrollIntoView(true);", link3) actions_chains = ActionChains(driver) actions_chains.move_to_element(link3) actions_chains.context_click(link3).perform() time.sleep(2) # actions_chains.context_click(link3).send_keys(Keys.ARROW_DOWN) # time.sleep(1) # actions_chains.context_click(link3).send_keys(Keys.ARROW_DOWN) # time.sleep(1) # actions_chains.context_click(link3).send_keys(Keys.ARROW_DOWN) # time.sleep(1) # actions_chains.context_click(link3).send_keys(Keys.ARROW_DOWN) # time.sleep(1) # actions_chains.context_click(link3).send_keys(Keys.ENTER) win32api.keybd_event(40, 0, 0, 0) win32api.keybd_event(40, 0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event(40, 0, 0, 0) win32api.keybd_event(40, 0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event(40, 0, 0, 0) win32api.keybd_event(40, 0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event(40, 0, 0, 0) # down win32api.keybd_event(40, 0, win32con.KEYEVENTF_KEYUP, 0) # down释放 time.sleep(2) win32api.keybd_event(13, 0, 0, 0) # enter win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键 except TimeoutException: print('TimeOut') except IOError: print('IOError') # except NameError: # print ('NameError') file_name = r'C:\gts\DData\seleniumdemo\chromedownload.exe' download_file = r'C:\gts\DData\seleniumdemo\autoit-v3-setup.exe' if is_file_existed(download_file): os.remove(download_file) #remove previous download file if is_file_existed(file_name): print("start to callback script:") os.system(file_name) else: driver.quit() raise "Script not found!" # leave time for download big size file while not is_file_existed(download_file): time.sleep(10) print("file [%s] download success" % (download_file)) driver.quit()
from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome( "E:\Python WebDriver\Ex1\WebdriverAPI\Driver\chromedriver.exe") driver.get("http://swisnl.github.io/jQuery-contextMenu/demo.html") driver.maximize_window() btnDouble = driver.find_element_by_xpath( "//span[contains(text(),'right click me')]") action = ActionChains(driver) action.context_click(btnDouble).perform() driver.quit()
def right_click_on_element(browser, element): act = ActionChains(browser) act.context_click(element).perform()
import keyboard from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome() driver.implicitly_wait(30) driver.get("https://www.google.com/") driver.maximize_window() parent = driver.current_window_handle print(parent) action = ActionChains(driver) Images = driver.find_element_by_xpath("//a[text()='Images']") action.context_click(Images).perform() keyboard.press("t") allhandles = driver.window_handles for handle in allhandles: if handle != parent: driver.switch_to.window(handle)
sc = webdriver.Firefox( executable_path= r"C:\Users\sony\PycharmProjects\SeleniumTestProj\Drivers\geckodriver.exe") print(type(sc)) sc.get("https://www.flipkart.com/") url = sc.current_url print(url) #Title title = sc.title print(title) uname = sc.find_element_by_xpath("//input[@class='_2zrpKA _1dBPDZ']") uname.send_keys("abcdefgh") pword = sc.find_element_by_xpath("//input[@class='_2zrpKA _3v41xv _1dBPDZ']") ac = ActionChains(sc) ac.double_click(uname).perform() ac.context_click(uname).perform() time.sleep(5) def enter(): keyboard.press("enter") keyboard.release("enter") def key_board(): time.sleep(2) keyboard.press("down arrow") keyboard.release("down arrow") for i in range(0, 5):
def context_click(self): with allure.step(f"右击 {self.describe}"): action = ActionChains(self.driver) action.context_click(self.present).perform() return self
from selenium import webdriver import time from selenium.webdriver import ActionChains driver = webdriver.Chrome(executable_path="C:\chromedriver\chromedriver.exe") # драйвер для Chrome driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html") button = driver.find_element_by_xpath("/html/body/div/section/div/div/div/p/span") actions = ActionChains(driver) actions.context_click(button).perform() # Нажатие правой кнопкой мыши time.sleep(4) driver.quit()
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from selenium.webdriver import ActionChains driver = webdriver.Chrome(executable_path="C:\Drivers\chromedriver_win32\chromedriver.exe") driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html") driver.maximize_window() right_click = driver.find_element_by_xpath("/html/body/div/section/div/div/div/p/span") actions = ActionChains(driver) actions.context_click(right_click).perform() # Mouse Right Click Action
# 1.导包 import time from selenium import webdriver from selenium.webdriver import ActionChains # 2.创建浏览器驱动对象 driver = webdriver.Chrome() driver.maximize_window() # 3.打开测试网址打开注册A.html页面,完成以下操作 driver.get( "file:///C:/Users/sandysong/Desktop/pagetest/%E6%B3%A8%E5%86%8CA.html") # 4.业务操作 driver.find_element_by_id("userA").send_keys("admin") mouse = ActionChains(driver) # 鼠标双击 mouse.double_click(driver.find_element_by_id("userA")) mouse.perform() time.sleep(2) # 鼠标右键 mouse.context_click(driver.find_element_by_id("userA")) mouse.perform() time.sleep(2) mouse.double_click(driver.find_element_by_id("userA")) mouse.perform() # 鼠标悬停 mouse.move_to_element(driver.find_element_by_tag_name("button")) mouse.perform() # 5.3秒后关闭浏览器窗口 time.sleep(3) driver.quit()
options.add_argument("--log-level=3") options.add_argument("--silent") options.add_argument("--no-sandbox") options.add_argument("--disable-logging") options.add_argument("--mute-audio") options.add_argument( '--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1' ) driver = webdriver.Chrome(executable_path=driverpth, options=options) driver.get("https://myanimelist.net") time.sleep(3) driver.find_element_by_xpath( "/html/body/div[10]/div/div/div/div[2]/button").click() driver.find_element_by_xpath( "/html/body/div[1]/div[1]/div/div/span[3]").click() driver.find_element_by_xpath( "/html/body/div[1]/div[1]/div/div/span[3]").send_keys('naruto') driver.find_element_by_xpath( "/html/body/div[1]/div[1]/div/div/span[3]").send_keys(Keys.ENTER) time.sleep(2) driver.find_element_by_xpath( "/html/body/div[1]/div[2]/div[3]/div[2]/div[2]/div[1]/div/article[1]/div[1]/div[2]/a[1]" ).click() time.sleep(2) source = driver.find_element_by_xpath( "/html/body/div[1]/div[2]/div[3]/div[2]/table/tbody/tr/td[1]/div/div[1]/a/img" ) action = ActionChains(driver) action.context_click(source).perform()
from selenium.webdriver import ActionChains driver = webdriver.Chrome() driver.implicitly_wait(5) driver.maximize_window() driver.get("http://demo.automationtesting.in/Register.html") time.sleep(2) switchTo = driver.find_element_by_xpath("//a[text()='SwitchTo']") windows_e = driver.find_element_by_xpath("//a[text()='Windows']") print("ActionChains object is created..") act = ActionChains(driver) print("Mouse Hovering..") #mouse Hover act.move_to_element(switchTo).move_to_element(windows_e).click().perform() time.sleep(3) #double click #driver.get("http://testautomationpractice.blogspot.com/") time.sleep(2) #copyText = driver.find_element_by_xpath("//button[text()='Click Me']") act.double_click(switchTo).perform() time.sleep(3) #Right Click act.context_click(switchTo).perform() # driver.save_screenshot("../newscreenshots") driver.quit()
def rightclick(self, element): acc = ActionChains(self.driver) acc.context_click(element).perform()
from selenium import webdriver from selenium.webdriver import ActionChains import os # define chromedriver path chromedriver_path = os.path.abspath( '../../drivers') + '\chromedriver_win32\chromedriver.exe' # create a chrome (driver) driver = webdriver.Chrome('C:/bin/chromedriver.exe') # Open portal and maximize window driver.get("https://the-internet.herokuapp.com/context_menu") driver.maximize_window() # find context menu and right-click on it actionChains = ActionChains(driver) actionChains.context_click(driver.find_element_by_id("hot-spot")).perform() # navigate to alert and click ok on it alert = driver.switch_to.alert print("Alert shows message: " + alert.text) alert.accept() # Close driver driver.close()
def test_inventory(self): inventory = self.driver.find_elements_by_name("Inventory") inventory.click() action = ActionChains(self.driver) action.context_click(inventory[1]).perform()
def test_1_add_folder(self): # заходим во вкладку "Папки" browser = self.driver link_folders = browser.find_element_by_css_selector('nav>div>ul>li') link_folders.click() # выбираем папку Избранное folder_favourites = browser.find_elements_by_css_selector('[class="group"]') folder_favourites[1].click() # выбираем кнопку Добавить add_data = browser.find_elements_by_css_selector('[type="button"]') add_data[2].click() # открываем выпадающий список типов объектов elem_kind = browser.find_element_by_css_selector('#kind') elem_kind.click() # добавляем запись # выбираем объект Папка add_data = browser.find_elements_by_css_selector('[value="F"]') add_data[0].click() # добавляем запись # Открывается карточка добавления нового объекта # вводим Название папки folder_name = browser.find_element_by_css_selector('#name') folder_name.click() folder_name_text = "_ 000_Новая тестовая папка" folder_name.clear() folder_name.send_keys(folder_name_text) # выбираем типы содержимого папки (Папка и Документ) content_of_folder1 = browser.find_element_by_css_selector('#F') content_of_folder1.click() content_of_folder2 = browser.find_element_by_css_selector('#D') content_of_folder2.click() # Сохраняем save_folder = browser.find_element_by_css_selector('[class="btn float-left save-icon text-white btn-secondary btn-sm"]') save_folder.click() # Удаляем созданную папку # Сортируем по названию #sort_folder = browser.find_elements_by_css_selector('[role="columnheader"]') #sort_folder[2].click() #Выбираем последнюю созданну папку choose1_folder = browser.find_elements_by_css_selector('[aria-colindex="3"]') actionChains = ActionChains(browser) actionChains.context_click(choose1_folder[-1]).perform() #choose1_folder[-1].context_click() time.sleep(2) #Нажимаем кнопку Удалить del_folder = browser.find_elements_by_css_selector('div>ul>li>span') del_folder[5].click() time.sleep(2) # Подтверждаем удаление del_folder_yes = browser.find_element_by_css_selector('footer>div>button') del_folder_yes.click()
def show_context_menu(self, element_to_right_click): actions = ActionChains(self.browser) actions.move_to_element(element_to_right_click) actions.context_click(element_to_right_click) actions.perform()
def run_ND(args): # Parameters raw_name = '../ND/raw' data_name = '../ND/data/data.csv' now = str(datetime.now()) r = requests.get( "https://www.health.nd.gov/diseases-conditions/coronavirus/north-dakota-coronavirus-cases" ).text soup = BeautifulSoup(r, "html.parser") url = soup.find('iframe')["src"] # Using Selenium # driver = webdriver.Safari() driver = webdriver.Chrome( executable_path="andrew/ChromeDriver/chromedriver.exe") driver.maximize_window() driver.get(url) time.sleep(10) out = {} # Change focus driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[51]/transform/div/div[3]/div/visual-modern' ).click() # Collect raw driver.save_screenshot(raw_name + "/overview_" + now + ".png") # New Tests, New Positive, Cum Tests, Cum Positive, Active Positives, % Population Tested out["Active Positive Cases"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[50]' ).text).replace(',', '').split('\n')[1]) out["New Tests: Total Processed"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[64]' ).text).replace(',', '').split('\n')[1]) out["New Tests: First Time Tested"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[135]' ).text).replace(',', '').split('\n')[1]) out["New Positives: Total"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[75]' ).text).replace(',', '').split('\n')[1]) out["New Positives: Tested Negative before Positive"] = int( (driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[66]' ).text).replace(',', '').split('\n')[1]) out["Total Tests"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[137]' ).text).replace(',', '').split('\n')[1]) out["Total Tested: Unique Individuals"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[139]' ).text).replace(',', '').split('\n')[1]) out["Total Positive Cases"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[141]' ).text).replace(',', '').split('\n')[1]) out["Total Positive Cases: Tested Negative before Positive"] = int( (driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[142]' ).text).replace(',', '').split('\n')[1]) out["Total Deaths"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[60]' ).text).replace(',', '').split('\n')[1]) out["Total Recovered"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[145]' ).text).replace(',', '').split('\n')[1]) # Age for Actives, Age for Positives driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[42]/transform/div/div[3]/div/visual-modern/div/button' ).click() time.sleep(7) out = get_age(out, driver, '# Positive Cases Age [', now, raw_name) driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[41]/transform/div/div[3]/div/visual-modern/div/button' ).click() time.sleep(7) out = get_age(out, driver, '# Active Cases Age [', now, raw_name) # Gender, Spreadtype, Race (Active and Cum Positives) driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[36]/transform/div/div[3]/div/visual-modern/div/button' ).click() time.sleep(7) out = get_gender_sp_race(out, driver, "Total Positive", now, raw_name) driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[34]/transform/div/div[3]/div/visual-modern/div/button' ).click() time.sleep(7) out = get_gender_sp_race(out, driver, "Total Active", now, raw_name) # Hospitalizations chart_div = driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[27]/transform/div/div[3]/div/visual-modern' ) driver.execute_script("arguments[0].scrollIntoView();", chart_div) # Raw driver.save_screenshot(raw_name + "/hosp_death_" + now + ".png") out["COVID Active Non-ICU"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[14]' ).text).replace(',', '').split('\n')[2]) out["COVID Total Non-ICU"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[13]' ).text).replace(',', '').split('\n')[2]) out["COVID Active ICU"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[17]' ).text).replace(',', '').split('\n')[1]) out["COVID Total ICU"] = int((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[15]' ).text).replace(',', '').split('\n')[1]) out["% Non-ICU occupied due to COVID"] = float((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[24]' ).text).replace('%', '').split('\n')[1]) out["% ICU occupied due to COVID"] = float((driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[25]' ).text).replace('%', '').split('\n')[1]) # Deaths by Age, Hospitalization by age # Hosp # Right Click chart_div = driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[23]/transform/div/div[3]/div' ) driver.execute_script("arguments[0].scrollIntoView();", chart_div) actionChains = ActionChains(driver) actionChains.context_click(chart_div).pause(3).send_keys( Keys.ENTER).perform() time.sleep(2) out = get_age_hosp(out, driver, now, "# Hospitalized Age [", raw_name) # Death # Right Click chart_div = driver.find_element_by_xpath( '//*[@id="pvExplorationHost"]/div/div/exploration/div/explore-canvas-modern/div/div[2]/div/div[2]/div[2]/visual-container-repeat/visual-container-modern[22]/transform/div/div[3]/div' ) driver.execute_script("arguments[0].scrollIntoView();", chart_div) actionChains = ActionChains(driver) actionChains.context_click(chart_div).pause(3).send_keys( Keys.ENTER).perform() time.sleep(2) out = get_age_death(out, driver, now, "# Deaths Age [", raw_name) out["Scrape_Time"] = str(datetime.now()) fields = sorted([x for x in out]) exists = os.path.exists(data_name) with open(data_name, "a") as fp: writer = csv.writer(fp) if not exists: writer.writerow(fields) writer.writerow([out[x] for x in fields])
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver import ActionChains from time import sleep driver = webdriver.Chrome( "E:\\Softwares\\My PC Apps\\Selenium Python\\Webdrivers\\chromedriver_win32\\chromedriver.exe" ) driver.maximize_window() driver.set_page_load_timeout(30) driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html") driver.implicitly_wait(20) act_chains = ActionChains(driver) right_click_ele = driver.find_element(By.XPATH, "//span[text()='right click me']") act_chains.context_click(right_click_ele).perform() right_click_options = driver.find_elements(By.CSS_SELECTOR, "li.context-menu-icon span") sleep(1) for opt in right_click_options: if opt.text == 'Edit': opt.click() driver.switch_to_alert().accept() sleep(1) driver.quit()
def click_button_right(self, element): action = ActionChains(self.driver) action.context_click(element).release().perform()
#### Mouse actions : Mouse Right Click from selenium import webdriver from selenium.webdriver import ActionChains import time driver = webdriver.Chrome( executable_path= 'D:\\Day Shift\\Zpyth\\Pseln\\External Libraries\\chromedriver_win32\\chromedriver.exe' ) driver.get('http://swisnl.github.io/jQuery-contextMenu/demo.html') driver.maximize_window() time.sleep(3) button = driver.find_element_by_xpath( '/html/body/div/section/div/div/div/p/span') # Mouse right click actions = ActionChains(driver) actions.context_click(button).perform() # right click action # driver.quit()
def rightClick(driver, element): act = ActionChains(driver) act.context_click(element).perform()
from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome( executable_path="C:\\Users\\Haroon\\Downloads\\chromedriver.exe") # driver.get("https://rahulshettyacademy.com/AutomationPractice/") driver.get( "https://chercher.tech/practice/practice-pop-ups-selenium-webdriver") driver.maximize_window() action = ActionChains(driver) # menu = driver.find_element_by_id("mousehover") # action.move_to_element(menu).perform() # childmenu = driver.find_element_by_link_text("Reload") # action.move_to_element(childmenu).perform() action.context_click(driver.find_element_by_id("double-click")).perform() action.double_click(driver.find_element_by_id("double-click")).perform() alert = driver.switch_to.alert assert "You double clicked me!!!, You got to be kidding me" == alert.text alert.accept()
#Click CSC General driver.find_element_by_xpath( '//*[@id="app-mount"]/div[4]/div[2]/div/div/div/div[1]/div/div[2]/div/div[2]/span' ).click() sleep(2) #Right Click Series # identifying the source element rightClickThis = driver.find_element_by_xpath( '/html/body/div/div[2]/div/div[2]/div/div/div/div[2]/div[1]/nav/div[1]/header/h1' ) # action chain object creation action = ActionChains(driver) # right click operation and then perform action.context_click(rightClickThis).perform() sleep(2) #Click CSC General driver.find_element_by_xpath( '/html/body/div/div[6]/div/div/div/div[9]/div[1]/div').click() sleep(2) # #There should be an option to select voice or text channel eventually. # if channeltype == 1: # driver.find_element_by_xpath('').click() # elif channeltype ==2: # driver.find_element_by_xpath('').click() driver.find_element_by_xpath( '/html/body/div/div[4]/div[2]/div/form/div/div/div[2]/div[2]/div/input'
# Below is the Code for double Clicking of mouse browser.get("https://demo.guru99.com/test/simple_context_menu.html") time.sleep(3) double_click_button = browser.find_element_by_xpath("") action = ActionChains(browser) action.double_click(double_click_button).perform() # Below is the Code for right clicking browser.get("https://www.google.co.in/") time.sleep(3) right_click_button = browser.find_element_by_xpath( "//*[@id='tsf']/div[2]/div[1]/div[1]/div/div[2]/input") action = ActionChains(browser) action.context_click(right_click_button).perform() time.sleep(3) # Below is the Code for drag and drop performed using mouse browser.get("https://demos.telerik.com/kendo-ui/dragdrop/index") source_element = browser.find_element_by_xpath('//*[@id="draggable"]') target_element = browser.find_element_by_xpath('//*[@id="droptarget"]') action = ActionChains(browser) action.drag_and_drop(source_element, target_element).perform() # Below is the code for Maximizing the screen browser.get("https://rifinder.com") time.sleep(3)