def UploadImageStory(file, story): try: elements = browser.find_elements_by_xpath("//*[@name='xhpc_message']") if len(elements) > 0: elements[0].click() sleep(2) input_photo = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.XPATH, "//*[@id='feedx_container']//*[@name='composer_photo[]']")) ) image_path = os.path.abspath(file) input_photo.send_keys(image_path) input_content = browser.find_element_by_xpath("//*[@id='feedx_container']//*[@role='combobox']") input_content.send_keys(story) send_button = WebDriverWait(browser, 10).until( EC.element_to_be_clickable((By.XPATH, "//*[@data-testid='react-composer-post-button']")) ) send_button.click() sleep(2) story_wrapper = browser.find_elements_by_css_selector('.userContentWrapper')[0] assert len(story_wrapper.find_elements_by_css_selector('.uiScaledImageContainer')) > 0 actual_story = story_wrapper.find_element_by_css_selector('.userContent p').text assert story in actual_story except : traceback.print_exc() browser.quit()
def add_Contact_simple(self, contact): self.driver.find_element_by_xpath("//order-details//tabset//div[2]/div/select").click() element = WebDriverWait(self.driver, 4).until( EC.visibility_of_element_located((By.XPATH, "//option[contains(text(), '%s')]" % contact)) ) element.click() self.driver.find_element_by_xpath("//order-details//div//div[1]/div[2]/div/span/button").click()
def add_Contact_from_contractor(self, contact): self.driver.find_element_by_xpath('//order-details//tabset/div/tab[2]//div[1]/div[2]/select').click() element = WebDriverWait(self.driver, 4).until( EC.element_to_be_clickable((By.XPATH, "//div[3]/select/option[contains(text(), '%s')]" % contact)) ) element.click() self.driver.find_element_by_xpath("//order-details//tabset//tab[2]//div[2]/button[1]").click()
def SendPhotoMessage(photo_url): try: chat_button = browser.find_element_by_css_selector('#fbDockChatBuddylistNub .fbNubButton') if chat_button.is_displayed(): chat_button.click() chat_list = WebDriverWait(browser, 5).until( EC.presence_of_element_located((By.CSS_SELECTOR, '.fbChatOrderedList ul li')) ) chat_list.click() chat_block = WebDriverWait(browser, 5).until( EC.presence_of_element_located((By.CSS_SELECTOR, '.fbNubFlyoutFooter div[role="textbox"]')) ) chat_block.click() # sleep(1) # clicked_attachment = browser.find_element_by_css_selector('form[title="加新相片"] div') # clicked_attachment.click() # attachment = WebDriverWait(browser, 5).until( # EC.presence_of_element_located((By.CSS_SELECTOR, 'input[name="attachment[]"]')) # ) sleep(2) attachment = browser.find_element_by_xpath('//*[@name="attachment[]"]') # browser.find_element_by_name('attachment[]').click( # browser.find_element_by_css_selector('input.hidde) image_path = os.path.abspath(photo_url) print image_path attachment.clear() attachment.send_keys("G:\\Game\\SoftwareTestingHW_3\\image.gif") except Exception, e: traceback.print_exc()
def deactivate_user(self, userName=None): #local locator _locDisabledStatusAction = (By.XPATH, "//button[@class='disabled status-action' and @name='action-deactivate']") #find the element associated with the given user user = self.__find_user(userName) if user is None: print "the given user is not found.\n" return False else: try: statusSelectButton = WebDriverWait(self.selenium,self._TimeOut). \ until(lambda s: user.find_element(*self._locStatusSelectButton)) except Exceptions.TimeoutException: print "the submit button was not found.\n" #check the current status of the button status = statusSelectButton.text if status == 'active': #the current status is active, so click the button for the deactivation statusSelectButton.click() try: deactivateButton = WebDriverWait(self.selenium,self._TimeOut). \ until(lambda s: user.find_element(*_locDisabledStatusAction)) #deactivateButton.click() deactivateButton.submit() except Exceptions.TimeoutException: print "the submit button was not found.\n" else: #the current status is inactive, so no further action is needed print "the user is already inactive.\n" return True
def delete_user(self, name=None): #local locators _locUser = (By.XPATH, "//h3[attribute::title='"+name+"']/preceding-sibling::div[attribute::class='controls']") _locDelButton = (By.CSS_SELECTOR, "button") #[H] move to the user page self.__move_to_user_page() #[M] find the user to leave out of the user list isGivenUserFound = False try: user = WebDriverWait(self.selenium,self._TimeOut). \ until(lambda s: self.find_element(*_locUser)) #take a delete action on the element delButton = WebDriverWait(self.selenium,self._TimeOut). \ until(lambda s: user.find_element(*_locDelButton)) isGivenUserFound = True except Exceptions.TimeoutException: print "let us move on..\n" if isGivenUserFound == True: #click the button delButton.click() #return the outcome in boolean return isGivenUserFound
def publish(link): driver.get(link) find_click(".org-module-link[href*=members]") type(".auto-search-input", username) l = lambda _driver: _driver.find_element_by_css_selector("a[href*=publicize]") elm = WebDriverWait(driver, 25).until(l) elm.click()
def test(self): FilterTermName = "Test Run" #click the "Manage" tab try: element = WebDriverWait(self.selenium,self._TimeOut). \ until(lambda s: self.find_element(*self._locManageTab)) except Exceptions.TimeoutException: Assert.fail(Exceptions.TimeoutException) element.click() #type in a filter term in the input field try: element = WebDriverWait(self.selenium, self._TimeOut) . \ until(lambda s: self.find_element(By.CSS_SELECTOR,"#text-filter")) except Exceptions.TimeoutException: Assert.fail(Exceptions.TimeoutException) element.send_keys(FilterTermName) try: elements = WebDriverWait(self.selenium, self._TimeOut) . \ until(lambda s: self.find_elements(By.CSS_SELECTOR,'a.suggestion.new')) except Exceptions.TimeoutException: Assert.fail(Exceptions.TimeoutException) for element in elements: TermName = element.find_element(By.CSS_SELECTOR, "b").text TermType = element.find_element(By.CSS_SELECTOR, "i").text if TermName == FilterTermName and TermType == "[description]": element.click()
def get_all_items(): #list to store alll scraped data all_items = list() #Display - read about pyvirtualdisplay display = Display(visible=0, size=(1024, 768)) display.start() #webdriver - read about selenium.webdriver driver = webdriver.Firefox() #this is a starting page we are scraping driver.get("http://www.federalreserve.gov/apps/reportforms/default.aspx") #Every element on the HTML page can be located using CSS selectors. #Opening the starting page in Chrome, right click on the drop-down menu, click "Inspect" we see a tag on the right highlighted, we copy it's id - MainContent_ddl_ReportForms #Knowing the id of dropdown menu, we can locate it with Selenium like this main_menu = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CSS_SELECTOR,"#MainContent_ddl_ReportForms"))) #Drop down menu is an HTML table of options which can be verified in Chrome browser (Developer Tools, that pop up when you right click and press "Inspect" on an element) #Following returns all of the options - rows in that table form_options = main_menu.find_elements_by_tag_name("option") #We count them option_count = len(form_options) #Next, we loop over all of them - essentially like we scrolling down the drop down menu and clicking on each every form for form_i in xrange(1,option_count): #Get web element corresponding to a form form = form_options[form_i] #Click as a mouse click-action in browser form.click() #Get text, because we need to store the form number form_id = form.text #Locate a web element corresponding to the submit button. By CSS selector which we found by inspection in Chrome browser (same logic as above) submit_button = WebDriverWait(driver,3).until(EC.presence_of_element_located((By.CSS_SELECTOR,"#MainContent_btn_GetForm"))) #Click as a mouse click-action in browser submit_button.click() #Prepare data structures to store all the info we want to scrape a = dict.fromkeys(['Description','OMB','Background','RespondentPanel','Frequency','PublicRelease']) #We are on a web page after submit-click, following will search for all items of interest. Or for corresponding #web-elements for el in a.keys(): try: item = driver.find_element_by_css_selector("#MainContent_lbl_"+el+"_data") #Once found it will store them in our dictionary, if not it will proceed to "except" section and do nothing a[el] = item.text except: #case when there is no such field pass #we need form number as well a['FormNumber'] = form_id #keeping them all in one list, which will have a dictionary per Form Number - and later, a row in your excel file per Form number all_items.append(a) #Ok, that part bothers me a little: it looks like I have to refresh "form_options" each time... #Otherwise I get following exception: selenium.common.exceptions.StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up driver.get("http://www.federalreserve.gov/apps/reportforms/default.aspx") main_menu = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CSS_SELECTOR,"#MainContent_ddl_ReportForms"))) form_options = main_menu.find_elements_by_tag_name("option") driver.close() display.stop() return all_items
def sendmail(self,recipients_popup="no"): #self.login() driver=self.driver element = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR,"b.nui-ico.fn-bg.ga0"))) element.click() if recipients_popup=="no": element = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR,"input.nui-editableAddr-ipt"))) element.send_keys(self.mail_to) else: element = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR,"input.nui-editableAddr-ipt"))) element.send_keys("d") #定位悬停的元素,点击填出的收件人 driver.find_element_by_class_name("nui-menu-item-text").click() #switch zhuti frame element = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.XPATH,"//section/header/div[2]/div[1]/div/div/input"))) element.send_keys(self.mail_topic) #swith to text iframe xf = driver.find_element_by_xpath('//*[@class="APP-editor-iframe"]') driver.switch_to_frame(xf) driver.find_element_by_css_selector("body.nui-scroll").send_keys("test1261_text") #back to default content and send email driver.switch_to_default_content()
def GoTo_Order_Of_Numb(self, OrdeNumb): self.Find_Order_of_Numb(OrdeNumb) element = WebDriverWait(self.driver, 5).until( EC.element_to_be_clickable((By.XPATH, "//orders//table/tbody/tr/td[2]/a[1]")) ) element.click() return PageOrder(self.driver)
def banner_save(self): self.wait_banner_image() element = WebDriverWait(self.driver, 30, 3).until( lambda el: el.find_element_by_css_selector(self.BANNER_SAVE) ) element.click()
def test_see_group(self): """ I should be able to log in as the first user. I should be able to see one group. When clicking on that group, I should be able to see 1 file for thar group. """ welcome_url = '%s%s' % (self.live_server_url, '/welcome') self.driver.get(welcome_url) css_selector_email="input#login_user_email" css_selector_password="******" css_selector_submit="button#auth_submit" css_selector_loginname="a#login-name" def try_to_login(user): self.bycss(css_selector_email).send_keys(user.email) self.bycss(css_selector_password).send_keys(user.password) self.bycss(css_selector_submit).click() element = WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_css_selector(css_selector_loginname)) self.assertEqual(element.text, "%s %s" % (user.firstname, user.lastname), "user name didn't match") try_to_login(User.objects.all().order_by("id")[0]) #try to login as first user. self.driver.get(self.live_server_url) a = self.bycss(".jstree-leaf[rel=ensemble][id_item='1']") ensemble_name=Ensemble.objects.get(pk=1).name self.assertEqual(a.text, ensemble_name, "ensemble name didn't match") #now try and click the link: a2 = a.find_element_by_tag_name("a") a2.click() file_elt = WebDriverWait(self.driver, 3).until(lambda x: x.find_element_by_css_selector(".filesview_ftitle>a")) self.assertEqual(file_elt.text, Source.objects.get(pk=1).title, "source title didn't match") file_elt.click() #check for instance that NB.pers.store.o.file[1].title is the same title pass
def search(self, query): self.ensure_login() self.driver.switch_to_default_content() try: nav_search = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.ID, 'nav-search')) ) nav_search.click() self.ensure_frame('suggest') form = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'form')) ) search_bar = form.find_element_by_tag_name('input') search_bar.send_keys(query) show_results = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.XPATH, '//*[@class="results"]/descendant::a')) ) show_results.click() self.driver.switch_to_default_content() wrapper = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, 'front')) ) iframe = wrapper.find_element_by_tag_name('iframe') self.driver.switch_to_frame(iframe) songs = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'tbody')) ) first_song = songs.find_element_by_tag_name('tr') first_song.click() first_song.send_keys(Keys.RETURN) except: print('Can\'t find element...') print(traceback.format_exc())
def test_partial_publication(self): self.login_author() self.selenium.get(self.live_server_url + self.ignored_part.get_absolute_url()) find_element = self.selenium.find_element_by_css_selector button = WebDriverWait(self.selenium, 20)\ .until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, '.readiness'))) readiness = button.get_attribute('data-is-ready') button.click() self.wait_element_attribute_change((By.CSS_SELECTOR, '.readiness'), 'data-is-ready', readiness, 20) self.content = PublishableContent.objects.get(pk=self.content.pk) self.ignored_part = self.content.load_version().children[1] self.assertFalse(self.ignored_part.ready_to_publish, 'part should be marked as not ready to publish') self.selenium.get(self.live_server_url + self.content.get_absolute_url()) self.selenium.get(self.live_server_url + self.ignored_part.get_absolute_url()) button = find_element('.readiness') self.assertNotEqual(readiness, button.get_attribute('data-is-ready'), 'part should be marked as not ready to publish') self.selenium.get(self.live_server_url + self.content.get_absolute_url()) self.ask_validation() self.logout() self.login_staff() self.take_reservation() self.validate() url = PublishedContent.objects.get(content__pk=self.content.pk).get_absolute_url_online() self.selenium.get(self.live_server_url + url) self.assertRaises(WebDriverException, find_element, 'a[href="{}"]'.format( reverse('tutorial:view-container', kwargs={ 'slug': self.content.slug, 'pk': self.content.pk, 'container_slug': self.ignored_part.slug })))
def test_edit_film(self): movieTitle = "Devchata" imdbNumber = "0134614" duration = "92" rating = "8.362" linkTrailer = "https://www.youtube.com/watch?v=LaCUkjlQuVw" year = "1961" driver = self.driver driver.get(self.base_url + "/php4dvd/") username = driver.find_element_by_id("username") username.send_keys("admin") password = driver.find_element_by_name("password") password.send_keys("admin") driver.find_element_by_name("submit").click() movie = WebDriverWait(self.driver, 30).until( EC.presence_of_element_located((By.CSS_SELECTOR, "#results div[title='" + movieTitle + "']")) ) movie.click() edit = WebDriverWait(self.driver, 30).until( EC.presence_of_element_located((By.CSS_SELECTOR, "#content nav ul li:nth-child(3) a")) ) edit.click() imdbidField = WebDriverWait(self.driver, 30).until( EC.presence_of_element_located((By.NAME, "imdbid")) ) imdbidField.send_keys(imdbNumber) durationField = driver.find_element_by_name("duration") durationField.send_keys(duration) ratingField = driver.find_element_by_name("rating") ratingField.send_keys(rating) trailerField = driver.find_element_by_name("trailer") trailerField.send_keys(linkTrailer) save = driver.find_element_by_id("submit") save.click(); h2Title = WebDriverWait(self.driver, 30).until( EC.presence_of_element_located((By.CSS_SELECTOR, ".maininfo_full h2")) ) self.assertEqual(h2Title.text, movieTitle + " (" + year + ")") driver.find_element_by_css_selector("#content nav ul li:nth-child(5) a").click() imdbidField2 = WebDriverWait(self.driver, 30).until( EC.presence_of_element_located((By.NAME, "imdbid")) ) durationField2 = driver.find_element_by_name("duration") ratingField2 = driver.find_element_by_name("rating") trailerField2 = driver.find_element_by_name("trailer") self.assertEqual(imdbidField2.get_attribute("value"), imdbNumber) self.assertEqual(durationField2.get_attribute("value"), duration) self.assertEqual(ratingField2.get_attribute("value"), rating) self.assertEqual(trailerField2.get_attribute("value"), linkTrailer)
def google_directions_select_travel_model_car(driver): """ Selects the travel car mode from selector @param driver: """ travel_mode_car_button = WebDriverWait(driver, MAX_TIMEOUT).until(EC.visibility_of_element_located((By.XPATH, "//*[@class='directions-travel-mode-selector']//*[@travel_mode='0']//button"))) travel_mode_car_button.click()
def google_directions_set_time_mode(driver): """ Sets the time mode to allow specify a date time for the request @param driver: """ time_listbox = WebDriverWait(driver, MAX_TIMEOUT).until(EC.visibility_of_element_located((By.XPATH, "//*[contains(@class,'time-anchoring-selector')]//*[@role='listbox']"))) time_listbox.click() time_listbox.find_element_by_xpath("//div[@id=':1']").click()
def test_browser_cache(self): """Test that browser caching is properly invalidated""" self.reviewboard_login('*****@*****.**', 'password') # Prime the browser cache. self.load_rburl('r/1') self.load_rburl('r/2') self.load_rburl('r/3') # Make a review to change the commit's status. self.load_rburl('r/3/diff/') ln = WebDriverWait(self.browser, 3).until( EC.visibility_of_element_located(( By.XPATH, "id('chunk0.0')/tr[1]/th[1]" ))) ActionChains(self.browser).move_to_element(ln).click(ln).perform() time.sleep(1) # Give time for the comment box to become focused ActionChains(self.browser).send_keys("Comment!").perform() save = self.browser.find_element_by_xpath( "//div[@class='comment-dlg-footer']/div[@class='buttons']/" "input[@class='save']") save.click() finish_btn = WebDriverWait(self.browser, 3).until( EC.visibility_of_element_located(( By.XPATH, "id('review-banner-edit')" ))) finish_btn.click() publish_btn = WebDriverWait(self.browser, 5).until( EC.visibility_of_element_located(( By.XPATH, "id('review-form-modalbox')/div[1]/div[2]/input[1]" ))) publish_btn.click() # Wait until we've been redirected to the reviews page WebDriverWait(self.browser, 3).until( EC.visibility_of_element_located((By.XPATH, "id('issue-summary')"))) # The Commit Table should show an issue count for the current # review requests status. status_el = self.get_commit_status(2) self.assertEqual(status_el.get_attribute('class'), 'issue-count') self.load_rburl('r/2') # The Commit Table shouldn't show a stale status for the second # commit even though no operations have been performed on the # first commit's review request. status_el = self.get_commit_status(2) self.assertEqual(status_el.get_attribute('class'), 'issue-count')
def update_hosts(): browser.get('https://my.noip.com/#!/dynamic-dns') def find_modify_host_buttons(): return browser.find_elements_by_css_selector('.modify-host-ddns-table') def has_modify_host_buttons(): return len(find_modify_host_buttons()) > 0 WebDriverWait(browser, 3).until( lambda _: has_modify_host_buttons(), 'Could not find any "Modify Host" buttons.') for i in range(len(find_modify_host_buttons())): def click_modify_host_button(): try: modify_host_button = find_modify_host_buttons()[i] # refresh modify_host_button.click() return True except StaleElementReferenceException: return False except WebDriverException as e: if 'Element is not clickable' in str(e): return False else: raise # NOTE: 3 and 6 seconds didn't seem to be enough time update_hostname_button = WebDriverWait(browser, 9).until( lambda _: click_modify_host_button(), 'Could not click "Modify Host" button.') def find_update_hostname_button(): buttons = browser.find_elements_by_css_selector('.btn-primary') update_hostname_buttons = [b for b in buttons if b.text == 'Update Hostname'] if len(update_hostname_buttons) != 1: return None (update_hostname_button,) = update_hostname_buttons return update_hostname_button update_hostname_button = WebDriverWait(browser, 3).until( lambda _: find_update_hostname_button(), 'Could not find unique "Update Hostname" button.') update_hostname_button.click() # HACK: Sometimes the "Update Hostname" button # fails to register the click... try: WebDriverWait(browser, 6).until( lambda _: not find_update_hostname_button()) except TimeoutException: # ...so try again in that situation find_update_hostname_button().click() WebDriverWait(browser, 6).until( lambda _: not find_update_hostname_button())
def parse(self, response): #response = TextResponse(url=response.url, body=self.driver.page_source, encoding='utf-8') sel = Selector(response) self.driver.get(response.url) i=0 while True: #next = self.driver.find_element_by_xpath('//*[@id="pagnNextString"]') next = WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located((By.ID, "pagnNextString")) ) #next.click() #i=i+1 #if(i==2): # break #sleep(50000) try: #self.driver.set_page_load_timeout(10000) response = TextResponse(url=response.url, body=self.driver.page_source, encoding='utf-8') sites = response.xpath('//*[@id="s-results-list-atf"]/li') for site in sites: '''item = EbayItem() item['title'] = site.xpath('//a/h2[@class="a-size-base a-color-null s-inline s-access-title a-text-normal"]/text()').extract() item['link'] = sel.xpath('//a/@href').extract() item['price'] = site.xpath('//span[@class="a-size-base a-color-price s-price a-text-bold"]/span/text()').extract() yield item''' item=EbayItem() #title = site.xpath('//a/h2[@class="a-size-base a-color-null s-inline s-access-title a-text-normal"]/text()').extract() item['title'] = site.xpath('div/div[2]/div[1]/a/h2/text()').extract() item['link'] = site.xpath('div/div[2]/div[1]/a/@href').extract() item['price'] = site.xpath('div/div[3]/div[0]/a/span[0]/text() | div/div[3]/div[1]/a/span/text() ').extract() item['image'] = site.xpath('div/div[1]/div/div/a/img/@src').extract() #item['rating'] = site.xpath('div/div[5]/span/span/a/i[1]/span/text() | div/div[4]/span/span/a/i[1]/span/text()').extract() item['rating'] = site.xpath('div//span[@class="a-icon-alt"]/text()').extract() #price = site.xpath('div/div[3]/div[0]/a/span[0]/text() | div/div[3]/div[1]/a/span/text() ').extract() #print title,link, price #print price #sleep(50000) yield item try: self.driver.find_element_by_xpath('//*[@id="pagnNextLink"]') except NoSuchElementException: break next.click() # get the data and write it to scrapy items except: #break a=10 #next.click() self.driver.close() #######
def del_Contactor(self): time.sleep(2) element1 = WebDriverWait(self.driver, 4).until( EC.element_to_be_clickable((By.XPATH, "//order-details//div/tab[2]//div[1]/div[1]/div/span/button/i")) ) element1.click() element2 = WebDriverWait(self.driver, 4).until( EC.element_to_be_clickable((By.XPATH, "//order-details/delete//div[3]/div[1]/button")) ) element2.click()
def add_Contractor(self, contact): self.driver.find_element_by_xpath('//order-details//tabset/div/tab[2]//div[1]/div[1]/select').click() element = WebDriverWait(self.driver, 4).until( EC.element_to_be_clickable((By.XPATH, "//order-details//tabset//tab[2]//div[1]/select/option[2]")) ) element.click() self.driver.find_element_by_xpath('//order-details//tabset/div/tab[2]//div[1]/div[2]/select').click() Search_contact = self.driver.find_element_by_xpath("//option[contains(text(), '%s')]" % contact) self.driver.execute_script("return arguments[0].scrollIntoView();", Search_contact) Search_contact.click()
def Change_Incoming_price(self, price): input = self.driver.find_element_by_xpath("//order-details//tabset//tab[3]/div[3]/div[2]//span/input") input.clear() input.click() input.send_keys(price) button = WebDriverWait(self.driver, 3).until( EC.element_to_be_clickable((By.XPATH, "//order-details//tabset/div/tab[3]/div[3]/div[2]//button[2]")) ) button.click() time.sleep(1)
def close(self): try: self.logger.log("Searching for invite friends popup") closer = WebDriverWait(self.browser, settings.wait_for_element_time).until( lambda driver: driver.find_element_by_xpath(self._close_xpath)) closer.click() except NoSuchElementException: self.logger.log("Invite friends popup not found") except TimeoutException: self.logger.log("Invite friends popup not found")
def set_image(self, img_path): banner_form_img = WebDriverWait(self.driver, 30, 0.1).until( lambda d: d.find_element_by_css_selector(self.IMAGE) ) banner_form_img.send_keys(img_path) save_img_button = WebDriverWait(self.driver, 30, 0.1).until( lambda d: d.find_element_by_css_selector(self.SAVE_BUTTON) ) save_img_button.click()
def LikePosts(user): try: like_button = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'a[data-testid="fb-ufi-likelink"]')) ) like_button.click() like_html_block = browser.find_element_by_css_selector('.UFIRow').get_attribute('innerHTML') assert user in like_html_block except Exception, e: traceback.print_exc() browser.quit()
def Delete_the_Product(self, Product): elements = self.Get_mass_Products() for elem in elements: product_name = elem.find_element_by_xpath('./span/a') if product_name.text == Product: elem.find_element_by_xpath('./button').click() Delite = self.Delite_form() element2 = WebDriverWait(Delite, 4).until( EC.element_to_be_clickable((By.XPATH, "./button")) ) element2.click() break
def Delete_the_component(self): panel = self.Define_Panel_button() button = WebDriverWait(panel, 3).until( EC.element_to_be_clickable((By.XPATH, "./button[3]")) ) button.click() time.sleep(1) Delite = self.Delite_form() element = WebDriverWait(Delite, 3).until( EC.element_to_be_clickable((By.XPATH, "./button")) ) element.click()
def add_groupBuy(self): # 点击添加团购 add_btn = ".btn.btn-default.btn-sm.modal-btn" browser.find_element_by_css_selector(add_btn).click() # 勾选桶装水,默认选中水票 locator = (By.CSS_SELECTOR, "#activitytype1") ele = WebDriverWait(browser, 4).until(EC.visibility_of_element_located(locator)) if ele is not False: print(ele) ele.click() else: pass # 定位当前页面所有的输入框 input_ele = "input.select2-search__field" inputList = browser.find_elements_by_css_selector(input_ele) # 绑定商品 inputList[0].send_keys("巴马") time.sleep(1) # 等待显示搜索结果 locator = (By.CSS_SELECTOR, "ul.select2-selection__rendered>li") WebDriverWait(browser, 4).until(EC.visibility_of_any_elements_located(locator)) goodsList = browser.find_elements_by_css_selector( "li[class^='select2-results__option']") # 类名以value值开头 resultText = goodsList[0].text if resultText == "未找到结果": pass else: goodsList[0].click() browser.find_element_by_id("scarePrice").send_keys("0.01") browser.find_element_by_id("scareNum").send_keys("5") # 获取当前时间 import datetime curTiem = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') delayTime = datetime.datetime.now() + datetime.timedelta(minutes=5) delayTimeF = delayTime.strftime('%Y-%m-%d %H:%M:%S') print("curTiem", curTiem) print("delayTimeF", delayTimeF) browser.find_element_by_id("endtime").send_keys(delayTimeF) browser.find_element_by_css_selector("input[id = 'name']").send_keys( "团购-桶装水小程序支付") # 发团人 inputList[1].send_keys("15220089922") time.sleep(1) # 等待显示搜索结果 locator = (By.CSS_SELECTOR, "ul.select2-selection__rendered>li") WebDriverWait(browser, 4).until(EC.visibility_of_any_elements_located(locator)) sponsorList = browser.find_elements_by_css_selector( "li[class^='select2-results__option']") # 类名以value值开头 resultText = sponsorList[0].text if resultText == "未找到结果": pass else: sponsorList[0].click() browser.find_element_by_css_selector(".btn.btn-primary").click() # 执行成功,需要关闭OK对话框 self.click_confirm_window()
def click_by_sele(self, by, locator): element = WebDriverWait(self.driver, 5, 0.5, ignored_exceptions=TimeoutException)\ .until(EC.element_to_be_clickable((by, locator))) element.click()
def click(self): element = WebDriverWait(self.driver, 10).until( ec.visibility_of_element_located(locator=self.locator)) element.click()
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC browser = webdriver.Firefox() browser.get('http://i.cqevi.net.cn/zfca/login') account_element = browser.find_element_by_css_selector("#username") account_element.click() account_element.send_keys("填写账号") password_element = browser.find_element_by_css_selector("#password") password_element.click() password_element.send_keys("填写密码") password_element.submit() schedule_element = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.ID, "129363840000054930"))) schedule_element.click()
def VisitGoodsPage(mongo_collection, driver, key, brand): # 初始化各个变量 url = brand['original_url'] try: driver.get(url) except WebDriverException as e: time.sleep(10) Logger.info('Error!' + str(e)) driver.quit() driver = loginTmall.login_tmall() driver.get(url) time.sleep(random.uniform(2, 4)) time.sleep(random.uniform(0.5, 1)) # 判断是否跳入了验证码 current_url = driver.current_url if 'https://sec.taobao.com' in current_url: collection_name = mongo_collection.name writeToCsv(url, brand, collection_name) time.sleep(random.uniform(2, 4)) return # 判断是否没有商品 if isNoItem(driver): return max_page = getMaxPage(driver) if max_page == 0: return Logger.info('最大页数:' + str(max_page)) print('准备访问商品页面') print('商品详细信息') time.sleep(random.uniform(2, 4)) driver.execute_script("scrollTo(0,1000)") time.sleep(random.uniform(1, 2)) driver.execute_script("scrollTo(0,5000)") time.sleep(random.uniform(1, 2)) driver.execute_script("scrollTo(0,10000)") time.sleep(random.uniform(1, 2)) # driver.execute_script("scrollTo(0,30000)") bs_obj = BeautifulSoup(driver.page_source, 'lxml') dealWith(mongo_collection, bs_obj, key, brand) N = 2 while N <= int(max_page): time.sleep(2) element = WebDriverWait( driver, 60).until(lambda driver: driver.find_element_by_xpath( "//a[@class='ui-page-s-next']")) element.click() time.sleep(2) driver.execute_script("scrollTo(0,1000)") time.sleep(1) driver.execute_script("scrollTo(0,5000)") time.sleep(1) driver.execute_script("scrollTo(0,10000)") time.sleep(1) # driver.execute_script("scrollTo(0,30000)") Logger.info(driver.current_url) # driver.execute_script("scrollTo(0,30000)") bs_obj = BeautifulSoup(driver.page_source, 'lxml') dealWith(mongo_collection, bs_obj, key, brand) # time.sleep(5) current_page = getCurrentPage(driver) Logger.info('完成当前页爬取:' + str(current_page)) if int(current_page) == int(max_page): Logger.info(brand['original_name']) Logger.info(''' ######################################################################### | 最大页数爬取完毕 | ######################################################################### ''') N = int(current_page) + 1 print("done..")
driver.switch_to.window(driver.window_handles[1]) pos = driver.find_element_by_css_selector(".name").text c_name = driver.find_element_by_css_selector(".company").text mony = driver.find_element_by_css_selector(".salary").text time = driver.find_element_by_css_selector( ".job_request p span:nth-child(3)").text print("职位名称:%s 公司名称:%s 薪资水平:%s 工作年限要求:%s " % (pos, c_name, mony, time)) driver.close() driver.switch_to.window(job_list) next_page = WebDriverWait(driver, 10).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '.item_con_pager .pager_container > *:last-child '))) # next_page=driver.find_element_by_css_selector(".item_con_pager .pager_container span:last-child") next_page_class = next_page.get_attribute('class') if 'pager_next_disabled' in next_page_class: print("页面全部完成") break else: print("当前第%d页,有%d个职位信息继续下一页" % (num, len(jobs))) next_page.click() time.sleep(3) num += 1 except AttributeError as a: print("'str' object has no attribute 'sleep") finally: time.sleep(10) print("爬虫结束") driver.quit()
'com.alibaba.android.rimet:id/et_phone_input').send_keys('13221833392') driver.find_element_by_id( 'com.alibaba.android.rimet:id/et_pwd_login').send_keys('!cheng12') # 登录 driver.find_element_by_id('com.alibaba.android.rimet:id/tv').click() print('登录成功...') # 协议 agree = (MobileBy.ACCESSIBILITY_ID, '同意') WebDriverWait(driver, 5).until( expected_conditions.presence_of_element_located(agree)).click() # 等待首页初始化 # print('等待首页加载20s...') # time.sleep(20) # 点击考勤打卡 punch = ( By.XPATH, '/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout[2]/android.widget.FrameLayout/android.widget.LinearLayout/android.view.ViewGroup/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.RelativeLayout/android.widget.FrameLayout/com.uc.webview.export.WebView/com.uc.webkit.be/android.webkit.WebView/android.view.View/android.view.View[6]/android.view.View[3]/android.view.View[1]/android.view.View[1]/android.view.View[1]/android.view.View' ) p = WebDriverWait(driver, 20).until( expected_conditions.presence_of_element_located(punch)) print('自动滑动...') driver.swipe(1 / 2 * el_x, 1 / 2 * el_y, 1 / 2 * el_x, 1 / 2 * el_y - 600 * el_y / 1920) p.click() # 权限处理 permission_allow()
def do_cloud_attach(self): button = WebDriverWait(self.driver, 1) \ .until(lambda driver: driver.find_element_by_xpath(self.FILE_ATTACH_CLOUD_ATTACH)) button.click()
class Page(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.indexUrl = 'https://movie.douban.com/' self.driver.get(self.indexUrl) def tearDown(self): self.driver.quit() # 登录默认正确的账号和密码 @unittest.skip('...') def test_login(self): login(self.driver) self.accountMsg = WebDriverWait( self.driver, 20, 0.2).until(lambda x: x.find_element_by_class_name('bn-more')).text self.assertEqual('小杨阳的帐号', self.accountMsg) logger.info('页面跳转成功') # @unittest.skip('...') def test_login_errorPassword(self): login(self.driver, '*****@*****.**', '123') self.accountMsg = self.driver.find_element_by_class_name( 'account-form-error').text logger.info('页面跳转成功') sleep(0.5) self.assertEqual('用户名或密码错误', self.accountMsg) # 搜索 @unittest.skip('...') def test_searchMovie(self): self.searchNav = self.driver.find_element_by_id('inp-query') self.searchNav.send_keys('少年的你') self.searchBtn = self.driver.find_element_by_xpath( '//*[@id="db-nav-movie"]/div[1]/div/div[2]/form/fieldset/div[2]/input' ) self.searchBtn.click() logger.info('页面跳转成功') self.title = WebDriverWait( self.driver, 20, 0.2 ).until(lambda x: x.find_element_by_xpath( '//*[@id="root"]/div/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/a') ) self.title.click() logger.info('页面跳转成功') self.subjectTitleText = self.driver.find_element_by_xpath( '//*[@id="content"]/h1/span[1]').text self.assertEqual('少年的你', self.subjectTitleText) @unittest.skip('...') def test_commentTmplPhone(self): login(self.driver) self.post1 = WebDriverWait( self.driver, 20, 0.2).until(lambda x: x.find_element_by_xpath( '//*[@id="screening"]/div[2]/ul/li[6]/ul/li[1]')) self.post1.click() logger.info('页面跳转成功') self.start5CommentBtn = WebDriverWait( self.driver, 20, 0.2).until(lambda x: x.find_element_by_id('star5')) self.start5CommentBtn.click() logger.info('页面跳转成功') self.tmplPhoneMsg = WebDriverWait(self.driver, 20, 0.2).until( lambda x: x.find_element_by_class_name('account-body-text')) self.assertEqual('验证手机号', self.tmplPhoneMsg)
def select_cloud_file(self, filename): print self.FILE_ATTACH_CLOUD_ELEMENT.format(filename) fileElement = WebDriverWait(self.driver, 2) \ .until(lambda driver: driver.find_elements_by_xpath(self.FILE_ATTACH_CLOUD_ELEMENT.format(filename))[0]) fileElement.click()
def selectLocaleChange(self): LocaleChange = WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.localeChange_ele)) time.sleep(1) LocaleChange.click()
# Dashboard page today_element = WebDriverWait(driver, 120, 1).until(expect.visibility_of_element_located((By.CLASS_NAME, "fc-today"))) ActionChains(driver).move_to_element(today_element).click().perform() # Log time pop-up hour_element = WebDriverWait(driver, 120, 1).until(expect.visibility_of_element_located((By.ID, "hour"))) hour_element.send_keys(working_time) selects = driver.find_elements_by_css_selector("input[placeholder='Type something']") hour_rate = selects[0] hour_rate.click() time.sleep(1) rate_option = WebDriverWait(driver, 120, 1)\ .until(expect.visibility_of_element_located((By.XPATH, "//*[text()=' " + hour_rate_to_fill + " ']"))) rate_option.click() activity = selects[1] activity.click() activity_option = WebDriverWait(driver, 120, 1)\ .until(expect.visibility_of_element_located((By.XPATH, "//*[text()=' " + activity_to_fill + " ']"))) activity_option.click() project = selects[2] project.click() project_option = WebDriverWait(driver, 120, 1)\ .until(expect.visibility_of_element_located((By.XPATH, "//*[text()=' " + project_to_fill + " ']"))) project_option.click() save_close_btn = driver.find_element_by_xpath("//*[text()=' Save & Close ']") save_close_btn.click()
firefox_profile = webdriver.FirefoxProfile() firefox_profile.set_preference('permissions.default.image', 2) firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false') driver = Firefox(firefox_profile=firefox_profile) """ driver.get(settings.login_data['login_url']) driver.find_element_by_id( "loginRegisterTabs").find_element_by_css_selector( 'ul:nth-child(1)').find_element_by_css_selector( 'li:nth-child(1)').click() driver.find_element_by_xpath('//input[@name="email"]').send_keys( settings.login_data['user_email']) driver.find_element_by_xpath('//input[@name="password"]').send_keys( settings.login_data['user_password']) driver.find_element_by_xpath('//button[@type="submit"]').click() play_button = WebDriverWait(driver, 15).until( lambda x: x.find_element_by_xpath('//span[@class="serverDetails"]')) play_button.click() driver.switch_to.window(driver.window_handles[1]) time.sleep( 15 ) # TODO: fix into an elegant solution, gotta wait for 'secureHash' in JS to be defined and set secureHash = utility.get_hash(driver.page_source) print(f"Logged in, our secure hash is {secureHash}") plan_manager()
#alert2 = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, '//button[contains(text(), "Not Now")]'))).click() #target the search input field searchbox = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search']"))) searchbox.clear() #search for the hashtag cat keyword = "#localhackday" searchbox.send_keys(keyword) time.sleep(5) # Wait for 5 seconds my_link = WebDriverWait(driver, 10).until( EC.element_to_be_clickable( (By.XPATH, "//a[contains(@href, '/" + keyword[1:] + "/')]"))) my_link.click() #scroll down 2 times #increase the range to sroll more n_scrolls = 2 for j in range(0, n_scrolls): driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(5) #target all the link elements on the page anchors = driver.find_elements_by_tag_name('a') anchors = [a.get_attribute('href') for a in anchors] #narrow down all links to image links only anchors = [ a for a in anchors if str(a).startswith("https://www.instagram.com/p/") ]
def choose_ticket_2(self): # for type 2, i.e., piao.damai.cn self.time_start = time() print("###开始进行日期及票价选择###") while self.driver.title.find( '订单结算页') == -1: # 如果跳转到了确认界面就算这步成功了,否则继续执行此步 self.num += 1 # 记录抢票轮数 if self.date != 0: # 如果要选择日期 datepicker = WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until( EC.presence_of_element_located( (By.CLASS_NAME, "month"))) datelist = datepicker.find_elements_by_tag_name( "span") # 找出所有日期 # print(len(datelist)) validlist = [] for i in range(len(datelist)): # 筛选出所有可选择日期 j = datelist[i] k = j.get_attribute('class') if k == 'itm z-show itm-undefined z-sel' \ or k == 'itm z-show itm-undefined' \ or k == 'itm itm-end z-show itm-undefined': validlist.append(j) # print(len(validlist)) validlist[self.date - 1].click() session = WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until( EC.presence_of_element_located( (By.ID, "performList"))) # session = self.driver.find_element_by_id('performList') session_list = session.find_elements_by_tag_name('li') # print('可选场次数量为:{}'.format(len(session_list))) for i in self.session: # 根据优先级选择一个可行场次,目前暂时没有找到有不可行日期的案例 j = session_list[i - 1] k = j.get_attribute('class').strip() if k == 'itm' or k == 'itm j_more': # 未选中 j.find_element_by_tag_name('a').click() break elif k == 'itm itm-sel' or k == 'itm j_more itm-sel': # 已选中 break elif k == 'itm itm-oos': # 无法选中 continue sleep(self.intersect_wait_time) price = WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until( EC.presence_of_element_located( (By.ID, "priceList"))) # price = self.driver.find_element_by_id('priceList') price_list = price.find_elements_by_tag_name('li') # print('可选票档数量为:{}'.format(len(price_list))) for i in self.price: j = price_list[i - 1] k = j.get_attribute('class').strip() if k == 'itm' or k == 'itm j_more': # 未选中 j.find_element_by_tag_name('a').click() break elif k == 'itm itm-sel' or k == 'itm j_more itm-sel': # 已选中 break elif k == 'itm itm-oos': # 无法选中 continue buybutton = None try: buybutton = self.driver.find_element_by_id( 'btnBuyNow') # 要改成立即预订按钮的id self.status = 3 except: try: buybutton = self.driver.find_element_by_id('btnBuyNow') self.status = 4 except: print('###无法立即购买,尝试自行选座###') try: buybutton = self.driver.find_element_by_id( 'btnXuanzuo') self.status = 5 print("###请自行选择位置和票价###") break except: print('---尚未开售,刷新等待---') self.status = 2 self.driver.refresh() # 需要先判断是否存在按钮,才能确定是否会出现添加票 if self.ticket_num > 1 and self.status not in [2, 5]: # 自动添加购票数 # add = self.driver.find_element_by_class_name('btn btn-add') add = WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until( EC.presence_of_element_located( (By.CLASS_NAME, "btn-add"))) for i in range(self.ticket_num - 1): add.click() buybutton.click()
usernameInput = driver.find_element_by_xpath("//input[@id='fm-login-id']") passwordInput = driver.find_element_by_xpath("//input[@id='fm-login-password']") loginBtn = driver.find_element_by_xpath("//button[@tabindex='3']") slideBtn = driver.find_element_by_xpath("//span[contains(@class,'btn_slide')]") # 输入账号 usernameInput.send_keys("邮箱/昵称/手机号码") time.sleep(1) # 输入密码 passwordInput.send_keys("密码") time.sleep(5) # 检查是否出现了滑动验证码 try: slider = driver.find_element_by_xpath("//span[contains(@class, 'btn_slide')]") if slider.is_displayed(): ActionChains(driver).click_and_hold(on_element=slider).perform() ActionChains(driver).move_by_offset(xoffset=258, yoffset=0).perform() ActionChains(driver).pause(0.5).release().perform() except Exception as e: print(e) # 点击登录按钮 button = WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.CLASS_NAME, 'password-login'))) button.click() time.sleep(2) print(driver.get_cookies())
driver.find_element_by_id('userPassword').send_keys(password) driver.find_element_by_xpath('//*[@id="account_login"]/form/div/div[5]/button').click() # 进入主页 while True: # 判断是不是在个人主页中。 if user_main_url in driver.current_url: break else: # 不在个人主页中就继续加载了。 time.sleep(1) my_space = WebDriverWait(driver, 500).until( lambda d: d.find_element_by_xpath('/html/body/div[2]/div/div[3]/a[2]')) my_space.click() # 点击进入写作页。 driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/div[1]/div[4]/a').click() time.sleep(1) # 填写标题 titleInput = driver.find_element_by_xpath('//*[@id="title"]') titleInput.send_keys(u'666666模333444444') # 填写内容 contentInput = driver.find_element_by_id('mdeditor') contentInput.send_keys(u'666666模拟3334444422222。。。。。')
class MainPage(BasePage): def __init__(self, driver): with allure.step("Finding components of the main page"): self.driver = driver webdriver_waiter = WebDriverWait(self.driver.instance, integers.default_timeout) self.body = webdriver_waiter.until( EC.presence_of_element_located( (By.ID, strings.general_id_body)), strings.id_is_not_present_timeout_message.format( strings.general_id_body)) self.header = WebDriverWait(self.body, integers.default_timeout).until( EC.visibility_of_element_located( (By.TAG_NAME, strings.html_tag_header)), strings.tag_timeout_message.format( strings.general_id_body, strings.html_tag_header)) self.home_btn = BasePage.find_button( self.header, (By.CSS_SELECTOR, strings.main_page_css_selector_home_btn)) self.new_tweet_btn = BasePage.find_button( self.header, (By.CSS_SELECTOR, strings.main_page_css_selector_new_tweet_btn)) self.main = WebDriverWait( self.body, integers.default_timeout).until( EC.visibility_of_element_located( (By.TAG_NAME, strings.html_tag_main)), strings.tag_timeout_message.format(strings.general_id_body, strings.html_tag_main)) self.primary_column = WebDriverWait( self.main, integers.default_timeout).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, strings.main_page_css_selector_primary_column)), strings.css_selector_timeout_message.format( strings.html_tag_main, strings.main_page_css_selector_primary_column)) self.sidebar_column = WebDriverWait( self.main, integers.default_timeout).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, strings.main_page_css_selector_sidebar_column)), strings.css_selector_timeout_message.format( strings.html_tag_main, strings.main_page_css_selector_sidebar_column)) self.modal_form_new_tweet = None self.draft_editor = None self.draft_editor_content = None self.toolbar = None self.tweet_btn = None self.own_tweets = [] @allure.step("Verify main buttons (home, new_tweet)") def validate_buttons(self): for temp_button in [self.home_btn, self.new_tweet_btn]: BasePage.validate_element_is_displayed_and_enabled( self, temp_button) @allure.step("Handle a modal form of new tweet") def get_modal_form_new_tweet(self): self.modal_form_new_tweet = WebDriverWait( self.driver.instance, integers.default_timeout).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, strings.main_page_css_selector_modal_form)), strings.assert_element_with_css_selector_is_not_presence. format(strings.main_page_css_selector_modal_form)) modal_form_waiter = WebDriverWait(self.modal_form_new_tweet, integers.default_timeout) self.draft_editor = modal_form_waiter.until( EC.visibility_of_element_located( (By.CLASS_NAME, strings.main_page_class_draft_editor)), strings.class_timeout_message.format( strings.main_page_css_selector_modal_form, strings.main_page_class_draft_editor)) self.draft_editor_content = WebDriverWait( self.draft_editor, integers.default_timeout).until( EC.visibility_of_element_located( (By.CLASS_NAME, strings.main_page_class_draft_editor_content)), strings.class_timeout_message.format( strings.main_page_class_draft_editor, strings.main_page_class_draft_editor_content)) self.toolbar = WebDriverWait( self.modal_form_new_tweet, integers.default_timeout).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, strings.main_page_css_selector_modal_form_toolbar)), strings.css_selector_timeout_message.format( strings.main_page_css_selector_modal_form, strings.main_page_css_selector_modal_form_toolbar)) self.tweet_btn = WebDriverWait( self.modal_form_new_tweet, integers.default_timeout).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, strings.main_page_css_selector_modal_form_tweet_btn)), strings.css_selector_timeout_message.format( strings.main_page_css_selector_modal_form, strings.main_page_css_selector_modal_form_tweet_btn)) @allure.step("Modal form is closed and removed from DOM") def modal_form_new_tweet_is_removed(self): WebDriverWait(self.driver.instance, integers.default_timeout).until( EC.staleness_of(self.modal_form_new_tweet), strings.assert_element_with_css_selector_is_presence.format( strings.main_page_css_selector_modal_form)) @allure.step("Get own tweets") def get_own_tweets(self): self.own_tweets = WebDriverWait( self.driver.instance, integers.default_timeout).until( EC.visibility_of_any_elements_located( (By.CSS_SELECTOR, strings.main_page_css_selector_own_tweet)), strings.assert_element_with_css_selector_is_not_presence. format(strings.main_page_css_selector_own_tweet)) @allure.step("Validate the added tweet") def validate_the_last_tweet(self, expected_string): spans = WebDriverWait(self.own_tweets[0], integers.default_timeout).until( EC.visibility_of_any_elements_located( (By.TAG_NAME, strings.html_tag_span)), strings.tag_timeout_message.format( strings.main_page_css_selector_own_tweet, strings.html_tag_span)) found = False for span in spans: if expected_string == span.text: found = True if not found: assert False, strings.main_page_own_tweet_is_nof_found.format( expected_string) @allure.step("Create a new tweet") def create_new_tweet(self, string_tweet="TEST"): with allure.step("Click on the 'New Tweet' button"): self.new_tweet_btn.click() self.get_modal_form_new_tweet() with allure.step("Set a tweet: {}".format(string_tweet)): self.draft_editor_content.send_keys(string_tweet) with allure.step("Verify a value of draft editor"): current_value = self.draft_editor.text assert current_value == string_tweet, strings.main_page_difference_in_values_assert_message. \ format(string_tweet, current_value) with allure.step("Click on the 'Tweet' button"): self.tweet_btn.click() self.modal_form_new_tweet_is_removed() self.get_own_tweets() self.validate_the_last_tweet(expected_string=string_tweet)
def test_autoland_inbound(self): # We should not be able to land to inbound without a HostingService # with an associated inbound repository. self.reviewboard_login('*****@*****.**', 'password2') self.load_rburl('r/1') autoland_btn = self.browser.find_element_by_id('autoland-trigger') self.assertEqual(autoland_btn.get_attribute('title'), 'Landing is not supported for this repository') self.add_hostingservice(1, 'Sirius Black', 'scm_level_1', True, 'try', True, 'inbound', '') # We should also not be able to land to inbound unless the review is # published. self.reviewboard_login('*****@*****.**', 'password2') self.load_rburl('r/1') autoland_btn = self.browser.find_element_by_id('autoland-trigger') self.assertEqual(autoland_btn.get_attribute('title'), 'Draft review requests cannot be landed') self.assign_reviewer(0, 'jsmith') publish_btn = WebDriverWait(self.browser, 3).until( EC.visibility_of_element_located((By.ID, 'btn-draft-publish'))) publish_btn.click() WebDriverWait(self.browser, 10).until( EC.invisibility_of_element_located((By.ID, 'draft-banner'))) # We should also not be able to land to inbound unless ship-it has # been granted. time.sleep(2) autoland_btn = self.browser.find_element_by_id('autoland-trigger') self.assertEqual( autoland_btn.get_attribute('title')[:39], 'Review request not approved for landing') self.ship_it(2, '*****@*****.**', 'password2') self.load_rburl('r/1') automation_menu = self.browser.find_element_by_id('automation-menu') automation_menu.click() autoland_btn = self.browser.find_element_by_id('autoland-trigger') self.assertEqual(autoland_btn.get_attribute('title'), '') # Clicking the button should display the autoland dialog autoland_btn.click() # Wait for commit rewrite response, which enables the submit btn autoland_submit_btn = WebDriverWait(self.browser, 10).until( EC.element_to_be_clickable((By.ID, 'autoland-submit'))) autoland_submit_btn.click() # autoland submission triggers a browser refresh, wait for that WebDriverWait(self.browser, 10).until( EC.visibility_of_element_located((By.CLASS_NAME, 'action-info'))) # Wait for autoland to process the request loading = True iteration = 0 while loading and iteration < 10: action_info = WebDriverWait(self.browser, 10).until( EC.visibility_of_element_located( (By.CLASS_NAME, 'action-info'))) loading = action_info.get_attribute('innerHTML').find( 'Waiting for the Autoland request') != -1 if loading: time.sleep(1) self.browser.refresh() iteration += 1 self.assertFalse(loading) # We should have closed the review request automatically submitted_banner = self.browser.find_element_by_id('submitted-banner') self.assertTrue('This change has been marked as submitted.' in submitted_banner.get_attribute('innerHTML')) # We should not be able to autoland from a closed review request try_btn = self.browser.find_element_by_id('autoland-try-trigger') self.assertEqual( try_btn.get_attribute('title'), 'You can not trigger a try build on a closed review request') autoland_btn = self.browser.find_element_by_id('autoland-trigger') self.assertEqual(autoland_btn.get_attribute('title'), 'You can not autoland from a closed review request')
# 3. 显式等待 WebDriverWait() # WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None) # 是针对指定的元素进行等待判定,需要通过from selenium.webdriver.support.wait import WebDriverWait导入模块 # driver : 所创建的浏览器对象 # timeout : 最长时间长度(默认单位:秒) # poll_frequency : 间隔检测时长(每)默认0.5秒 # ignored_exceptions : 超时后的异常信息,默认情况下抛NoSuchElementException异常。 driver.get('https://www.baidu.com') # 3.1 与until()或者until_not()方法结合使用 # 调用该方法提供的驱动程序作为参数,直到返回值为True或False # WebDriverWait(driver,10).until(method,message="") # WebDriverWait(driver,10).until_not(method,message="") # 另外,lambda提供了一个运行时动态创建函数的方法,匿名函数。 driver.find_element_by_id('kw').send_keys('Selenium 自学网') # element = WebDriverWait(driver, 5, 0.5).until(lambda x: x.find_element_by_id("su")) element = WebDriverWait(driver, 5, 0.5).until(lambda x: x.find_element_by_id("su111"), message='未找到该元素!嘿嘿') # 3.2 与expected_conditions结合使用 element = WebDriverWait(driver, 5, 0.5).until(EC.presence_of_element_located( (By.ID, 'su')), message="") element.click() sleep(3) driver.quit() # 注意:当隐式等待和显示等待一起被使用时,系统的等待时间取决于最长的等待时间。 # WebDriverWait元素等待和全局设置:https://zhuanlan.zhihu.com/p/143357537
def click(self): element = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(locator=self.locator)) element.click() return None
def test_9_Footer(self): Facebook = WebDriverWait(self.driver, 60).until(EC.element_to_be_clickable((By.ID, "Facebook"))) Facebook.click() Twitter = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.ID, "Twitter"))) Twitter.click() Google = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.ID, "Google"))) Google.click() Instagram = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.ID, "Instagram"))) Instagram.click() LinkedIn = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.ID, "Linkedin"))) LinkedIn.click() GitHub = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.ID, "GitHub"))) GitHub.click() time.sleep(1)
def extractDetails(self): yelp_name = 'none' yelp_url = '' yelp_reviews = '' yelp_friends = '' yelp_city = '' yelp_elite = '' email = self.input_data.pop()[1] logTxt = "+-+-+-+-+-+-+-+- {0} +-+-+-+-+-+-+-+-\n".format(email) driver = self.drivers.pop() if driver is None: driver = webdriver.Chrome(os.getcwd() + '/WebDriver/chromedriver.exe') driver.maximize_window() driver.get(self.start_url) try: login = WebDriverWait(driver, 100).until( EC.presence_of_element_located(( By.CSS_SELECTOR, "a.header-nav_link.header-nav_link--log-in.js-analytics-click" ))) login.click() login = WebDriverWait(driver, 100).until( EC.presence_of_element_located( (By.CSS_SELECTOR, "form#ajax-login > input#email"))) password = driver.find_element_by_css_selector( 'form#ajax-login > input#password') submit_btn = driver.find_element_by_css_selector( 'form#ajax-login > button.submit') login.send_keys(id) time.sleep(5) password.send_keys(pw) time.sleep(5) submit_btn.click() logTxt = logTxt + '\tLogin Successfully!\n' self.handle = driver.current_window_handle self.url = driver.current_url usr_btn = WebDriverWait(driver, 100).until( EC.element_to_be_clickable(( By.CSS_SELECTOR, "span.icon.icon--14-triangle-down.icon--size-14.icon--inverse." "icon--fallback-inverted.u-triangle-direction-down." "user-account_button-arrow.responsive-visible-large-inline-block" ))) usr_btn.click() find_friends = WebDriverWait(driver, 100).until( EC.presence_of_all_elements_located( (By.CSS_SELECTOR, "ul.drop-menu-group--nav.drop-menu-group > li"))) find_friends[1].click() except: logTxt = logTxt + "\tWe can't access to first page of yelp\n" print(logTxt) self.drivers.append(None) return try: query = WebDriverWait(driver, 100).until( EC.presence_of_element_located( (By.XPATH, "//input[@name='query']"))) except: logTxt = logTxt + "\tCan't find query inputbox\n" print(logTxt) self.drivers.append(driver) return try: action_chain = ActionChains(driver) action_chain.click(query).key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).send_keys(Keys.DELETE) \ .perform() query.send_keys(email) query.send_keys(Keys.ENTER) except: logTxt = logTxt + "\tCan't input email into query inputbox\n" print(logTxt) self.drivers.append(driver) return try: WebDriverWait(driver, 100).until( EC.presence_of_element_located( (By.CSS_SELECTOR, "div.section-header_block-main"))) member_row = driver.find_element_by_css_selector("div.member-row") try: yelp_name = member_row.find_element_by_id( "dropdown_user-name").text except: yelp_name = '' try: yelp_url = member_row.find_element_by_id( "dropdown_user-name").get_attribute('href') except: yelp_url = '' try: yelp_city = member_row.find_element_by_class_name( "li.user-location.responsive-hidden-small").text except: yelp_city = '' try: yelp_friends = member_row.find_element_by_class_name( "li.friend-count.responsive-small-display-inline-block" ).text except: yelp_friends = '' try: yelp_reviews = member_row.find_element_by_class_name( "li.review-count.responsive-small-display-inline-block" ).text except: yelp_reviews = '' try: yelp_elite = member_row.find_element_by_class_name( "li.review-count.responsive-small-display-inline-block") yelp_elite = 'yes' except: yelp_elite = 'no' except: logTxt = logTxt + "\tCan't find details\n" logTxt = logTxt + "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + \ "\tYelp Name: {0}\n\tYelp URL: {1}\n\tYelp Reviews: {2}\n\tYelp Friends: {3}\n\tYelp City: {4}\n" \ "\tYelp Elite: {5}\n".format(yelp_name, yelp_url, yelp_reviews, yelp_friends, yelp_city, yelp_elite) print(logTxt) self.output_data.append([ yelp_name, yelp_url, yelp_reviews, yelp_friends, yelp_city, yelp_elite ]) self.drivers.append(driver)
print(f"Found a new word: {word.text}") for en in en_words: de = en_de_dict[en] try: button_en = WebDriverWait(driver, 0).until( EC.visibility_of_element_located( (By.XPATH, f"//button[contains(@class, 'selectable-token') and text()='{en}'][not(@disabled)]")) ) button_de = WebDriverWait(driver, 0).until( EC.visibility_of_element_located( (By.XPATH, f"//button[contains(@class, 'selectable-token') and text()='{de}'][not(@disabled)]")) ) if button_en and button_de: matched_pairs += 1 button_en.click() button_de.click() except: print(f"{en}/{de} not found.") if matched_pairs == 5: break continue_button = WebDriverWait(driver, 20).until( EC.visibility_of_element_located( (By.XPATH, "//button[@class='continue'][not(@disabled)]")) ).click() time.sleep(pause) continue_button = WebDriverWait(driver, 5).until( EC.visibility_of_element_located( (By.XPATH, "//button[@class='continue end-slides-continue-button'][not(@disabled)]"))
divstr='/html/body/form/table/tbody/tr/td/table/tbody/tr[6]/td/table/tbody/tr['+str(divTemp)+']/td[7]' resultLocator=(By.XPATH,divstr) qyname=WebDriverWait(driver, 1).until(EC.presence_of_element_located(resultLocator)).text divstr='//*[@id="form1"]/table/tbody/tr/td/table/tbody/tr[6]/td/table/tbody/tr['+str(divTemp)+']/td[5]' resultLocator=(By.XPATH,divstr) zztemp=WebDriverWait(driver, 1).until(EC.presence_of_element_located(resultLocator)).text #资质为空则跳过 if zztemp!='无' : namehref = driver.current_url divstr = '//*[@id="form1"]/table/tbody/tr/td/table/tbody/tr[6]/td/table/tbody/tr[' + str( divTemp) + ']/td[5]' resultLocator = (By.XPATH, divstr) zztemp = WebDriverWait(driver, 1).until(EC.presence_of_element_located(resultLocator)).text linkbt.click() handle = driver.current_window_handle handles = driver.window_handles for newhandle in handles: if newhandle != handle: driver.switch_to.window(newhandle) # init&姓名 divstr = '//*[@id="XM"]' resultLocator = (By.XPATH, divstr) name=WebDriverWait(driver, 120).until(EC.presence_of_element_located(resultLocator)).text # 注册类 zcflag = True zctemp = 1 #获取单个资质时 try:
from selenium.webdriver import Firefox from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from unittest import TestCase driver = Firefox() driver.get("https://www.12306.cn/index") sleep(5) # 修改日期 code = "ele=document.querySelector('#train_date');ele.readOnly='False';ele.value='2019-09-10';" driver.execute_script(code) # 填写出发点 sleep(2) ele = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, 'fromStationText'))) ele.click() ele.send_keys('成都') ele = driver.find_element_by_xpath( "//div[@id='panel_cities']//span[text()='成都']") ac = ActionChains(driver) ac.move_to_element(ele).click().perform() # driver.find_element_by_xpath("//div[@id='panel_cities']//span[text()='成都']").click() # # 目的地 ele = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, 'toStationText'))) ele.send_keys('达州') # driver.find_element_by_xpath("//div[@id='panel_cities']//span[text()='达州']").click() ele = driver.find_element_by_xpath( "//div[@id='panel_cities']//span[text()='达州']") ac = ActionChains(driver) ac.move_to_element(ele).click().perform()
))) span = span1[li].find_element_by_tag_name("span") print(span.text) span1[li].click() main_container = WebDriverWait(browser, 10).until( EC.presence_of_element_located(( By.XPATH, "//div[@class='jsx-1143766650 product-discovery min-height70']" ))) mobile_containers = main_container.find_elements_by_xpath( "//*[@class='jsx-1143766650 layout horizontal center-center card-margin ']" ) no_of_pagedowns = 10 while no_of_pagedowns: elem.send_keys(Keys.PAGE_DOWN) time.sleep(0.2) no_of_pagedowns -= 1 # print(len(mobile_containers)) for mobile_container in range(len(mobile_containers)): print(mobile_containers[mobile_container].text) no_of_pagedowns = 10 while no_of_pagedowns: elem.send_keys(Keys.PAGE_UP) time.sleep(0.2) no_of_pagedowns -= 1 close = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.XPATH, "//*[@class='jss357']"))) close.click()
def passLogin(self): ''' chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--incognito") driver = webdriver.Chrome(executable_path=os.getcwd() + '/WebDriver/chromedriver.exe', chrome_options=chrome_options) ''' driver = webdriver.Chrome(executable_path=os.getcwd() + '/WebDriver/chromedriver.exe') driver.maximize_window() driver.get(self.url) print("Go to 'https://radius.unionrealtime.com/home'.") signin_btns = WebDriverWait(driver, 200).until( EC.presence_of_all_elements_located( (By.CSS_SELECTOR, "button.btn.btn-clear.btn-lg"))) signin_btns[1].click() print("Clicked 'SIGN IN'.") # print(driver.page_source) time.sleep(5) WebDriverWait(driver, 200).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, "div.auth0-lock-cred-pane.auth0-lock-quiet"))) time.sleep(5) email_in = WebDriverWait(driver, 200).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, "div.auth0-lock-input-email > div > input"))) action_chain = ActionChains(driver) action_chain.click(email_in).send_keys(self.email).perform() time.sleep(5) print("Put email.") pass_in = WebDriverWait(driver, 500).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, "div.auth0-lock-input-password > div > input"))) action_chain = ActionChains(driver) action_chain.click(pass_in).send_keys(self.password).perform() time.sleep(3) print("Put password.") login_btn = WebDriverWait(driver, 200).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, "button.auth0-lock-submit"))) login_btn.click() print("Clicked login button.") time.sleep(10) self.drivers.append(driver)
def button(self, ele): wait = WebDriverWait(self.driver, 10).until(ec.presence_of_element_located(ele)) wait.click()
def launchChange(self): change = WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.launchChange_ele)) time.sleep(1) change.click()
def UploadVideoStory(file, story): try: elements = browser.find_elements_by_xpath("//*[@name='xhpc_message']") if len(elements) > 0: elements[0].click() sleep(2) input_photo = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.XPATH, "//*[@id='feedx_container']//*[@name='composer_photo[]']")) ) image_path = os.path.abspath('image.gif') input_photo.send_keys(image_path) input_photo = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.XPATH, "//*[@id='feedx_container']//*[@name='composer_photo[]']")) ) image_path = os.path.abspath(file) input_photo.send_keys(image_path) send_button = WebDriverWait(browser, 15).until( EC.element_to_be_clickable((By.XPATH, "//*[@data-testid='react-composer-post-button']")) ) send_button.click() wait_for_video_alert = WebDriverWait(browser, 5).until( EC.presence_of_element_located((By.XPATH, '//*[@role="dialog"]')) ) close_button = WebDriverWait(browser, 5).until( EC.element_to_be_clickable((By.CSS_SELECTOR, '.layerCancel')) ) close_button.click() except : traceback.print_exc()