Python selenium.webdriver.common.by.By.ID Examples

The following are 30 code examples of selenium.webdriver.common.by.By.ID(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module selenium.webdriver.common.by.By , or try the search function .
Example #1
Source File: ris.py    From uncaptcha with MIT License 11 votes vote down vote up
def start_captcha():
    driver = webdriver.Firefox()
    driver.get("http://reddit.com")
    driver.find_element(By.XPATH, "//*[@id=\"header-bottom-right\"]/span[1]/a").click()
    time.sleep(1)
    driver.find_element(By.ID, "user_reg").send_keys("qwertyuiop091231")
    driver.find_element(By.ID, "passwd_reg").send_keys("THISISMYPASSWORD!!$")
    driver.find_element(By.ID, "passwd2_reg").send_keys("THISISMYPASSWORD!!$")
    driver.find_element(By.ID, "email_reg").send_keys("biggie.smalls123@gmail.com")
    #driver.find_element_by_tag_name("body").send_keys(Keys.COMMAND + Keys.ALT + 'k')
    iframeSwitch = driver.find_element(By.XPATH, "//*[@id=\"register-form\"]/div[6]/div/div/div/iframe")
    driver.switch_to.frame(iframeSwitch)
    driver.find_element(By.ID, "recaptcha-anchor").click()
    # download captcha image
    # 
    # split payload
    # 
    # reverse_search
    # 
    # driver.quit()

# determines if an image keywords matches the target keyword
# uses the synonyms of the image keyword 
Example #2
Source File: eastmoney_crawler.py    From eastmoney_spider with MIT License 8 votes vote down vote up
def index_page(page):
    try:
        print('正在爬取第: %s 页' % page)
        wait.until(
            EC.presence_of_element_located((By.ID, "dt_1")))
        # 判断是否是第1页,如果大于1就输入跳转,否则等待加载完成。
        if page > 1:
            # 确定页数输入框
            input = wait.until(EC.presence_of_element_located(
                (By.XPATH, '//*[@id="PageContgopage"]')))
            input.click()
            input.clear()
            input.send_keys(page)
            submit = wait.until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, '#PageCont > a.btn_link')))
            submit.click()
            time.sleep(2)
        # 确认成功跳转到输入框中的指定页
        wait.until(EC.text_to_be_present_in_element(
            (By.CSS_SELECTOR, '#PageCont > span.at'), str(page)))
    except Exception:
        return None 
Example #3
Source File: bots.py    From Dallinger with MIT License 7 votes vote down vote up
def participate(self):
        random.seed(self.worker_id)
        chatbot = random.choice(self.PERSONALITIES)
        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.ID, "send-message"))
        )
        logger.info("Entering participate method")
        start = time.time()
        while (time.time() - start) < self.TOTAL_CHAT_TIME:

            self.wait_to_send_message()
            history = self.get_chat_history()
            logger.info("History: %s" % history)
            if history and history[-1]:
                logger.info("Responding to: %s" % history[-1])
                output = chatbot.respond(history[-1])
            else:
                logger.info("Using random greeting.")
                output = random.choice(self.GREETINGS)
            logger.info("Output: %s" % output)
            self.send_message(output)

        self.leave_chat() 
Example #4
Source File: crawler_cei.py    From ir with Mozilla Public License 2.0 7 votes vote down vote up
def __login(self):
        if self.debug: self.driver.save_screenshot(self.directory + r'01.png')
        txt_login = self.driver.find_element_by_id('ctl00_ContentPlaceHolder1_txtLogin')
        txt_login.clear()
        txt_login.send_keys(os.environ['CPF'])

        time.sleep(3.0)
        txt_senha = self.driver.find_element_by_id('ctl00_ContentPlaceHolder1_txtSenha')
        txt_senha.clear()
        txt_senha.send_keys(os.environ['SENHA_CEI'])
        time.sleep(3.0)

        if self.debug: self.driver.save_screenshot(self.directory + r'02.png')

        btn_logar = self.driver.find_element_by_id('ctl00_ContentPlaceHolder1_btnLogar')
        btn_logar.click()

        try:
            WebDriverWait(self.driver, 60).until(EC.visibility_of_element_located((By.ID, 'objGrafPosiInv')))
        except Exception as ex:
            raise Exception('Nao foi possivel logar no CEI. Possivelmente usuario/senha errada ou indisponibilidade do site')

        if self.debug: self.driver.save_screenshot(self.directory + r'03.png') 
Example #5
Source File: TraTicketBooker.py    From TRA-Ticket-Booker with GNU General Public License v3.0 7 votes vote down vote up
def submit_user_data(self):
        # Submit to Authent-Number Page (press button).
        wait = WebDriverWait(self.driver, timeout=6)
        try:
            self.driver.execute_script(
                'document.getElementsByTagName("button")[0].click()'
            )
            wait.until(
                EC.presence_of_element_located(
                    (By.ID, 'idRandomPic')
                )
            )
        except:
            self.label_show_result.setText(
                '【連線逾時或是網路不穩定】\n' + 
                '【請檢查網路環境以及是否為尖峰時段。】'
            ) 
Example #6
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def test_wait_until_first_element_is_found_timeout(driver_wrapper, utils):
    # Configure driver mock
    driver_wrapper.driver.find_element.side_effect = NoSuchElementException('Unknown')
    element_locator = (By.ID, 'element_id')

    start_time = time.time()
    with pytest.raises(TimeoutException) as excinfo:
        utils.wait_until_first_element_is_found([element_locator])
    end_time = time.time()

    assert 'None of the page elements has been found after 10 seconds' in str(excinfo.value)
    # find_element has been called more than one time
    driver_wrapper.driver.find_element.assert_called_with(*element_locator)
    # Execution time must be greater than timeout
    assert end_time - start_time > 10 
Example #7
Source File: crawler_advfn.py    From ir with Mozilla Public License 2.0 6 votes vote down vote up
def __recupera_tipo_ticker(self):
        WebDriverWait(CrawlerAdvfn.driver, 10).until(EC.visibility_of_element_located((By.ID, 'quoteElementPiece5')))
        tipo = CrawlerAdvfn.driver.find_element_by_id('quoteElementPiece5').text.lower()

        if tipo == 'futuro':
            return TipoTicker.FUTURO

        if tipo == 'opção':
            return TipoTicker.OPCAO

        if tipo == 'preferencial' or tipo == 'ordinária':
            return TipoTicker.ACAO

        if tipo == 'fundo':
            if self.__fundo_eh_fii():
                return TipoTicker.FII

            if self.__fundo_eh_etf():
                return TipoTicker.ETF

        return None 
Example #8
Source File: apw_internal.py    From tir with MIT License 6 votes vote down vote up
def SwitchModal(self, option, frame=''):
        '''
        Sets the focus in a modal object
        '''
        try:
            time.sleep(2)
            self.driver.switch_to.default_content()
            self.driver.implicitly_wait(30)
            modaldupGuia = self.wait.until(EC.presence_of_element_located((By.ID, "modal-content")))

            if modaldupGuia.is_displayed():
                btn = self.driver.find_element_by_xpath("//button[contains(text(), '%s')]" % option)
                btn.click()
            else:
                time.sleep(2)
                if modaldupGuia.is_displayed():
                    btn = self.driver.find_element_by_xpath("//button[contains(text(), '%s')]" % option)
                    btn.click()
        except Exception as e:
            self.log_error(str(e)) 
Example #9
Source File: acceptance_helpers.py    From biweeklybudget with GNU Affero General Public License v3.0 6 votes vote down vote up
def wait_until_clickable(self, driver, elem_id, by=By.ID, timeout=10):
        """
        Wait for the modal to be shown.

        :param driver: Selenium driver instance
        :type driver: selenium.webdriver.remote.webdriver.WebDriver
        :param elem_id: element ID
        :type elem_id: str
        :param by: What method to use to find the element. This must be one of
          the strings which are values of
          :py:class:`selenium.webdriver.common.by.By` attributes.
        :type by: str
        :param timeout: timeout in seconds
        :type timeout: int
        """
        WebDriverWait(driver, timeout).until(
            EC.element_to_be_clickable((by, elem_id))
        ) 
Example #10
Source File: apw_internal.py    From tir with MIT License 6 votes vote down vote up
def get_web_value(self, element):
        """
		Gets the informations of field based in the ID
        """

        if element.tag_name == "div":
            element_children = element.find_element(By.CSS_SELECTOR, "div > * ")
            if element_children is not None:
                element = element_children

        if element.tag_name == "label":
            web_value = element.get_attribute("text")
        elif element.tag_name == "select":
            current_select = int(element.get_attribute('value'))
            selected_element = element.find_elements(By.CSS_SELECTOR, "option")[current_select]
            web_value = selected_element.text
        else:
            web_value = element.get_attribute("value")

        return web_value 
Example #11
Source File: test_reconcile.py    From biweeklybudget with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_08_invalid_trans_id(self, base_url, selenium):
        self.get(selenium, base_url + '/reconcile')
        assert self.get_reconciled(selenium) == {}
        script = 'reconciled[1234] = [4, "OFXNONE"];'
        selenium.execute_script(script)
        assert self.get_reconciled(selenium) == {
            1234: [4, "OFXNONE"]
        }
        # click submit button
        selenium.find_element_by_id('reconcile-submit').click()
        sleep(1)
        self.wait_for_jquery_done(selenium)
        assert self.get_reconciled(selenium) == {
            1234: [4, "OFXNONE"]
        }
        msg = selenium.find_element_by_id('reconcile-msg')
        assert msg.text == 'Error 400: Invalid Transaction ID: 1234'
        assert 'alert-danger' in msg.get_attribute('class') 
Example #12
Source File: readcomic.py    From ReadComicOnline-Downloader with MIT License 6 votes vote down vote up
def Single_Issue(url,Quality):
	#print url
	print 'Quality To Download : ',Quality[0]
	print 'Order To Download : ',Quality[1]
	#sys.exit()
	#print url,' This is first'
	
	browser = webdriver.PhantomJS(service_args=['--load-images=no'])
	browser.get(url)
	try:
		element = WebDriverWait(browser, 10).until(
			EC.presence_of_element_located((By.ID, "stSegmentFrame"))
		)
		#print 'Downloading the whole page! Will take some time, please don\'t close this script...\n'
		#print 'I\'ve waited long enough'
	except Exception, e:
		#raise e
		browser.save_screenshot('Single_exception.png')
		print e
		pass 
Example #13
Source File: pytest_dallinger.py    From Dallinger with MIT License 6 votes vote down vote up
def wait_for_text(driver, el_id, value, removed=False, timeout=10):
    el = wait_for_element(driver, el_id, timeout)
    if value in el.text and not removed:
        return el
    if removed and value not in el.text:
        return el

    wait = WebDriverWait(driver, timeout)
    condition = EC.text_to_be_present_in_element((By.ID, el_id), value)
    if removed:
        wait.until_not(condition)
        if value not in el.text:
            return el
    else:
        wait.until(condition)
        if value in el.text:
            return el

    raise AttributeError 
Example #14
Source File: bots.py    From Dallinger with MIT License 6 votes vote down vote up
def sign_off(self):
        """Submit questionnaire and finish.

        This uses Selenium to click the submit button on the questionnaire
        and return to the original window.
        """
        try:
            logger.info("Bot player signing off.")
            feedback = WebDriverWait(self.driver, 20).until(
                EC.presence_of_element_located((By.ID, "submit-questionnaire"))
            )
            self.complete_questionnaire()
            feedback.click()
            logger.info("Clicked submit questionnaire button.")
            self.driver.switch_to_window(self.driver.window_handles[0])
            self.driver.set_window_size(1024, 768)
            logger.info("Switched back to initial window.")
            return True
        except TimeoutException:
            logger.error("Error during experiment sign off.")
            return False 
Example #15
Source File: pyats_android.py    From solutions_examples with Apache License 2.0 6 votes vote down vote up
def failure_check(self):
        no_7 = self.driver.find_element(value="digit_7", by=By.ID)
        no_7.click();
        plus = self.driver.find_element(value="op_add", by=By.ID)
        plus.click();
        no_4 = self.driver.find_element(value="digit_4", by=By.ID)
        no_4.click();
        equalTo = self.driver.find_element(value="eq", by=By.ID)
        equalTo.click();

        results = self.driver.find_element(value="formula", by=By.ID)
        result_value = results.get_attribute('text')
        if result_value == '12':
            self.passed('Value is 12')
        else:
            self.failed('Value is not 12') 
Example #16
Source File: slipsomat.py    From alma-slipsomat with MIT License 6 votes vote down vote up
def close_letter(self):
        # If we are at specific letter, press the "go back" button.
        elems = self.worker.all(By.CSS_SELECTOR, '.pageTitle')
        if len(elems) != 0:
            title = elems[0].text.strip()
            if title == 'Configuration File':
                try:
                    backBtn = self.worker.first(By.ID, 'PAGE_BUTTONS_cbuttonback')
                    backBtn.click()
                except NoSuchElementException:
                    pass
                try:
                    backBtn = self.worker.first(By.ID, 'PAGE_BUTTONS_cbuttonnavigationcancel')
                    backBtn.click()
                except NoSuchElementException:
                    pass

            self.worker.wait_for(By.CSS_SELECTOR, '#TABLE_DATA_fileList') 
Example #17
Source File: pyats_android.py    From solutions_examples with Apache License 2.0 6 votes vote down vote up
def pass_check(self):
        no_7 = self.driver.find_element(value="digit_7", by=By.ID)
        no_7.click();
        plus = self.driver.find_element(value="op_add", by=By.ID)
        plus.click();
        no_4 = self.driver.find_element(value="digit_4", by=By.ID)
        no_4.click();
        equalTo = self.driver.find_element(value="eq", by=By.ID)
        equalTo.click();
        results = self.driver.find_element(value="formula", by=By.ID)
        result_value = results.get_attribute('text')
        if result_value == '11':
            self.passed('Value is 11')
        else:
            self.failed('Value is not 11')

    # Second test section 
Example #18
Source File: slipsomat.py    From alma-slipsomat with MIT License 5 votes vote down vote up
def is_customized(self, filename):
        index = self.filenames.index(filename)
        updated_by = self.worker.first(By.ID, 'SPAN_SELENIUM_ID_fileList_ROW_%d_COL_cfgFileupdatedBy' % index)

        return updated_by.text not in ('-', 'Network') 
Example #19
Source File: slipsomat.py    From alma-slipsomat with MIT License 5 votes vote down vote up
def open(self):
        try:
            self.worker.first(By.ID, 'cbuttonupload')
        except NoSuchElementException:
            self.worker.get('/mng/action/home.do')

            # Open Alma configuration
            self.worker.wait_for_and_click(By.CSS_SELECTOR, '#ALMA_MENU_TOP_NAV_configuration')
            self.worker.click(By.XPATH, '//*[@href="#CONF_MENU6"]')  # text() = "General"
            self.worker.click(By.XPATH, '//*[text() = "Notification Template"]')

            self.worker.wait_for(By.ID, 'cbuttonupload') 
Example #20
Source File: slipsomat.py    From alma-slipsomat with MIT License 5 votes vote down vote up
def put_contents(self, filename, content):
        """
        Save letter contents to Alma.

        This method assumes the letter has already been opened.
        """
        self.assert_filename(filename)

        # The "normal" way to set the value of a textarea with Selenium is to use
        # send_keys(), but it took > 30 seconds for some of the larger letters.
        # So here's a much faster way:
        txtarea = self.worker.first(By.ID, 'pageBeanfileContent')
        txtarea_id = txtarea.get_attribute('id')

        value = content.text.replace('"', '\\"').replace('\n', '\\n')
        script = 'document.getElementById("%s").value = "%s";' % (txtarea_id, value)
        self.worker.driver.execute_script(script)

        # Submit the form
        try:
            btn = self.worker.first(By.ID, 'PAGE_BUTTONS_cbuttonsave')
        except NoSuchElementException:
            btn = self.worker.first(By.ID, 'PAGE_BUTTONS_cbuttoncustomize')
        btn.click()

        # Wait for the table view.
        # Longer timeout per https://github.com/scriptotek/alma-slipsomat/issues/33
        self.worker.wait_for(By.CSS_SELECTOR, '.typeD table', timeout=40)

        return True


# Commands --------------------------------------------------------------------------------- 
Example #21
Source File: slipsomat.py    From alma-slipsomat with MIT License 5 votes vote down vote up
def assert_filename(self, filename):
        # Assert that we are at the right letter
        element = self.worker.wait.until(
            EC.presence_of_element_located((By.ID, 'pageBeanconfigFilefilename'))
        )
        elt = element.text.replace('../', '')
        assert elt == filename, "%r != %r" % (elt, filename) 
Example #22
Source File: tntapi.py    From 20up with GNU General Public License v3.0 5 votes vote down vote up
def getAllAlbums(self):
        """
        Get all the albums for the given user.
        An album is a shortlist of three elements (name, number, link), where
        <name> is the name of the album itself, <number> is the number of
        pictures in the album and <link> is the url of the album.

        Returns:
            A list of albums.
        """
        self.driver.get(URLS['my_profile'])

        trigger = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, 'albumSelector')))
        
        if self.driver.current_url != URLS['my_profile']:
            return None
        
        trigger.click()
        
        myAlbums = []
        
        soup = BeautifulSoup(self.driver.page_source, 'html.parser')
        allAlbums = soup.find('ul', {'class': INFOS['albums']}).find_all('a', {'class': INFOS['classAlbums']})
        for album in allAlbums:
            withoutSpace = album.getText().split()
            name = normalize(' '.join(withoutSpace[:-1]).replace(' ','-'))
            intNumber = withoutSpace[-1][1:-1]
            if intNumber.find('.') != -1:
                intNumber = intNumber.split('.')
            else:
                intNumber = intNumber.split(',')
            finalNumber = ''
            for num in intNumber:
                finalNumber += num
            number = int(finalNumber)
            link = album['href']
            
            nnl = [name, number, TWENTY_HOST + link]
            myAlbums.append(nnl)

        return myAlbums 
Example #23
Source File: experiment.py    From Dallinger with MIT License 5 votes vote down vote up
def participate(self):
        """Finish reading and send text"""
        try:
            logger.info("Entering participate method")
            ready = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, "finish-reading"))
            )
            stimulus = self.driver.find_element_by_id("stimulus")
            story = stimulus.find_element_by_id("story")
            story_text = story.text
            logger.info("Stimulus text:")
            logger.info(story_text)
            ready.click()
            submit = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, "submit-response"))
            )
            textarea = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, "reproduction"))
            )
            textarea.clear()
            text = self.transform_text(story_text)
            logger.info("Transformed text:")
            logger.info(text)
            textarea.send_keys(text)
            submit.click()
            return True
        except TimeoutException:
            return False 
Example #24
Source File: tntapi.py    From 20up with GNU General Public License v3.0 5 votes vote down vote up
def waitForLogin(self):
        """
        Wait for the user to be logged into the social network.
        """
        logged = False
        while not logged:
            try:
                WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, 'sideBarPlaceHolder')))
                logged = True
            except:
                pass 
Example #25
Source File: experiment.py    From Dallinger with MIT License 5 votes vote down vote up
def participate(self):
        """Finish reading and send text"""
        try:
            while True:
                left = WebDriverWait(self.driver, 10).until(
                    EC.element_to_be_clickable((By.ID, "left_button"))
                )
                right = WebDriverWait(self.driver, 10).until(
                    EC.element_to_be_clickable((By.ID, "right_button"))
                )

                random.choice((left, right)).click()
                time.sleep(1.0)
        except TimeoutException:
            return False 
Example #26
Source File: acceptance_helpers.py    From biweeklybudget with GNU Affero General Public License v3.0 5 votes vote down vote up
def wait_for_id(self, driver, id):
        """
        Wait for the element with ID ``id`` to be shown.

        :param driver: Selenium driver instance
        :type driver: selenium.webdriver.remote.webdriver.WebDriver
        :param id: ID of the element
        :type id: str
        """
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, id))
        ) 
Example #27
Source File: bots.py    From Dallinger with MIT License 5 votes vote down vote up
def sign_up(self):
        """Accept HIT, give consent and start experiment.

        This uses Selenium to click through buttons on the ad,
        consent, and instruction pages.
        """
        try:
            self.driver.get(self.URL)
            logger.info("Loaded ad page.")
            begin = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.CLASS_NAME, "btn-primary"))
            )
            begin.click()
            logger.info("Clicked begin experiment button.")
            WebDriverWait(self.driver, 10).until(lambda d: len(d.window_handles) == 2)
            self.driver.switch_to_window(self.driver.window_handles[-1])
            self.driver.set_window_size(1024, 768)
            logger.info("Switched to experiment popup.")
            consent = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, "consent"))
            )
            consent.click()
            logger.info("Clicked consent button.")
            participate = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.CLASS_NAME, "btn-success"))
            )
            participate.click()
            logger.info("Clicked start button.")
            return True
        except TimeoutException:
            logger.error("Error during experiment sign up.")
            return False 
Example #28
Source File: tntapi.py    From 20up with GNU General Public License v3.0 5 votes vote down vote up
def getComments(self):
        """
        Get the comments of the current picture.
            
        Returns:
            A list of comments of the picture, where a <comment> is a shortlist
            with the comment itself (<user date: comment>).
        """
        while True:
            try:
                more = WebDriverWait(self.driver, 1).until(EC.presence_of_element_located((By.ID, INFOS['viewMore'])))
                more.click()
            except:
                break
        
        soup = BeautifulSoup(self.driver.page_source, 'html.parser')
        myComments = []
        try:
            allComments = soup.find('ol', {'id': INFOS['picComments']}).find_all('li')
            for comment in allComments:
                try:
                    myComments.append(comment.get_text(separator=' ').replace(' Eliminar', ':'))
                except:
                    pass
        except:
            pass
            
        return myComments 
Example #29
Source File: pytest_dallinger.py    From Dallinger with MIT License 5 votes vote down vote up
def wait_until_clickable(driver, el_id, timeout=10):
    return WebDriverWait(driver, timeout).until(
        EC.element_to_be_clickable((By.ID, el_id))
    ) 
Example #30
Source File: test_reconcile.py    From biweeklybudget with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_09_invalid_trans(self, base_url, testdb):
        res = requests.post(
            base_url + '/ajax/reconcile',
            json={'reconciled': {32198: [2, 'OFX3']}, 'ofxIgnored': {}}
        )
        assert res.json() == {
            'success': False,
            'error_message': 'Invalid Transaction ID: 32198'
        }
        assert res.status_code == 400
        assert len(testdb.query(TxnReconcile).all()) == 2