예제 #1
0
def typing(driver: Browser):
    driver.implicitly_wait(0)

    symbols = driver.find_elements(tag='span',
                                   classname='incomplete',
                                   loose_match=False)
    input = driver.find_elements(css_selector='div.letters.notranslate')[0]

    passage = ""
    for s in symbols:
        passage += s.get_attribute('innerHTML')

    input.send_keys(passage)
예제 #2
0
def visual_memory(driver: Browser):
    round = 3
    time.sleep(.75)
    container = driver.find_elements(css_selector='div.css-hvbk5q.eut2yre0')[0]
    while round <= 52:
        squares = container.find_elements_by_xpath('.//*//*')
        activeSquares = []
        for square in squares:
            if 'active' in square.get_attribute('class'):
                activeSquares.append(square)
        time.sleep(1)
        for square in activeSquares:
            square.click()
        round += 1
        time.sleep(1.8)

    #Fail out on purpose
    for i in range(3):
        squares = container.find_elements_by_xpath('.//*//*')
        activeSquares = []
        for square in squares:
            if 'active' not in square.get_attribute('class'):
                activeSquares.append(square)
        time.sleep(1)
        for square in activeSquares[:3]:
            square.click()
        time.sleep(1.8)
예제 #3
0
def sequence_memory(driver: Browser):
    driver.implicitly_wait(0.01)

    squares = driver.find_elements(tag='div', css_selector='div.square')

    roundNo = 1
    squaresNotFound = True
    squareOrder = []
    failSquare = squares[0]
    while roundNo <= 38:
        while squaresNotFound:
            for square in squares:
                if square.get_attribute('class') == 'square active':
                    if len(squareOrder) > 0:
                        if square == squareOrder[-1]:
                            break
                    squareOrder.append(square)
                    if len(squareOrder) == roundNo:
                        squaresNotFound = False
                elif roundNo == 1:
                    failSquare = square

            time.sleep(0.05)

        time.sleep(0.5)
        for square in squareOrder:
            square.click()
            time.sleep(0.001)

        roundNo += 1
        squareOrder = []
        squaresNotFound = True
    time.sleep(1 * roundNo)
    failSquare.click()
예제 #4
0
def reaction_time(driver: Browser):
    clickArea = driver.find_elements(
        tag='div', css_selector='div.e18o0sx0.css-saet2v.e19owgy77')[0]

    round = 1
    while round <= 5:
        if 'view-go' in clickArea.get_attribute('class'):
            clickArea.click()
            round += 1
            clickArea.click()
            time.sleep(0.2)
예제 #5
0
def scanFacebookPage(url):
    if 'facebook.com' in url:
        web = Browser()
        web.go_to(url)
        try:
            pagina = web.find_elements(id='content')

            for elem in pagina[0].find_elements_by_tag_name('a'):
                if elem.get_attribute('href'):
                    getEvent(elem.get_attribute('href'))

        except:
            print(url,"Nu am putut colecta toate datele")
예제 #6
0
def number_memory(driver: Browser):
    round = 1
    while round <= 23:
        num = driver.find_elements(
            css_selector='div.big-number')[0].get_attribute('innerHTML')
        time.sleep((1 * round) + 0.7)
        driver.type(num)
        driver.click('Submit')
        driver.click('NEXT')
        round += 1
    time.sleep((1 * round) + 0.7)
    driver.type(str(int(num) - 1))
    driver.click('Submit')
예제 #7
0
def getEvent(url):

    if 'facebook.com/events/' in url:
        web = Browser()
        web.go_to(url)
        try:
            newEvent = Event()
            pagina = web.find_elements(id='content_container')

            eventHead= pagina[0].find_element_by_id('event_header')
            primary= eventHead.find_element_by_id('event_header_primary')
            link= primary.find_element_by_tag_name('img').get_attribute('src')
            titlu= primary.find_element_by_id('seo_h1_tag').text
            newEvent.title=titlu

            newEvent.tags= tags_controller.get_Tags(newEvent.title)

            newEvent.image_link=link

            sumar= eventHead.find_element_by_id('event_summary')
            data= sumar.find_element_by_id('event_time_info')

            for x in data.find_elements_by_css_selector("*"):
               if x.get_attribute('content'):
                    y = x.get_attribute('content').split('to')
                    newEvent.date = parser.parse(y[0])

            x= data.find_element_by_xpath("./following-sibling::li")
            location= x.text[x.text.find('\n'):x.text.rfind('\n')]
            newEvent.location=location


            detalii=pagina[0].find_element_by_id('reaction_units')
            for elem in detalii.find_elements_by_css_selector("*"):
                if elem.get_attribute('data-testid') == 'event-permalink-details':
                    newEvent.description = elem.text
                    newEvent.tags+= tags_controller.get_Tags(newEvent.description)

            if detalii.find_element_by_tag_name('ul'):
                newEvent.tags += tags_controller.get_Tags(detalii.find_element_by_tag_name('ul').text)

            newEvent.put()

            web.close_current_tab()

        except :
            print("Nu am putut colecta toate datele")
    else:
        print('Bad url')
예제 #8
0
def chimp_test(driver: Browser):
    driver.implicitly_wait(0.00001)

    roundNo = 4
    squareOrder = []
    while roundNo <= 40:
        for i in range(1, roundNo + 1):
            squareOrder.append(
                driver.find_elements(text=str(i), tag='div', number=1))

        for i, square in enumerate(squareOrder):
            square[0].find_element_by_xpath('./..').click()

        roundNo += 1
        squareOrder = []
        driver.click('Continue')
예제 #9
0
def verbal_memory(driver: Browser):
    driver.implicitly_wait(0)

    wordElementParent = driver.find_elements(
        tag='div', css_selector='div.css-1qvtbrk.e19owgy78',
        loose_match=False)[1]
    round = 1
    words = []
    while round <= 1000:
        word = wordElementParent.get_attribute('innerHTML')[19:-6]
        if word in words:
            driver.click(text='SEEN')
        else:
            words.append(word)
            driver.click(text='NEW')
        round += 1

    for i in range(3):
        word = wordElementParent.get_attribute('innerHTML')[19:-6]
        if word in words:
            driver.click(text='NEW')
        else:
            driver.click(text='SEEN')
예제 #10
0
파일: bot.py 프로젝트: robertanye/webbot
class Bot:
    __metaclass__ = ABCMeta
    web = None

    def __init__(self):
        with open("config.json") as json_file:
            self.config = json.load(json_file)
            logger.info("email " + self.config['email'])
            logger.info("password  " + self.config['password'])
            logger.info("url  " + self.config['url'])
            logger.info("max price " + str(self.config['max price']))
        self.web = Browser()

    def send_email(self, subject, body):
        message = """ 
        Subject: CCI Primers Available
        
        Found CCI Primers
        
        """
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
            server.login(self.config['email'], self.config['email_pwd'])
            server.sendmail(self.config['email'], self.config['email'],
                            message)

    @abstractmethod
    def restock_check(self):
        """
        This method should be defined in a derived class as it
        is different for different sites
        :return:
        """

    @abstractmethod
    def checkout(self):
        """
        This method should be defined in a derived class as it is
        is different for different sites
        :return:
        """

    @abstractmethod
    def signout(self):
        """
        only defined in the derived class
        :return:
        """

    def search(self, product):
        self.web.type(product, into="Search")
        self.web.press(self.web.Key.ENTER)
        results = self.web.find_elements(classname="product-finding-container")
        logger.info("Found " + results)

    @abstractmethod
    def check_for_available(self):
        """
        only defined in the derived class
        :return:
        """

    @abstractmethod
    def checkout(self):
        '''

        '''
        # finish the buy

    @abstractmethod
    def add_to_cart(self):
        """
        only defined in the derived class
        :return:
        """

    def price_check(self):
        price = self.get_price()
        if price == -1:
            return False

        if price <= self.config['max price']:
            return True
        else:
            return False

    @abstractmethod
    def get_price(self):
        """
        only defined in the derived class
        :return:
        """

    def get_config(self):
        return self.config
예제 #11
0
import datetime
import os

now = datetime.datetime.now()
directory = now.strftime("%Y-%m-%d")

if not os.path.exists(directory):
    os.makedirs(directory)

web = Browser()
web.go_to(
    "https://www.idealista.com/alquiler-habitacion/alcobendas-madrid/con-precio-hasta_500/"
)
time.sleep(2)
for habitaciones in range(
        0, len(web.find_elements(tag='article', classname='item'))):
    web.find_elements(tag='article', classname='item')[habitaciones].click()
    time.sleep(1)
    x = web.get_current_url()
    filename = '{}/{}'.format(directory, x[35:-1])
    if not os.path.exists(filename):
        os.makedirs(filename)
        filenameurl = '{}/{}.txt'.format(filename, 'url')
        f = open(filenameurl, "w+")
        f.write(web.get_current_url())
        f.write("\r\n")
        filenameinfo = '{}/{}.txt'.format(filename, 'info')
        f = open(filenameinfo, "w+")
        f.write(
            web.find_elements(tag='section', classname='detail-info')[0].text)
        f.write("\r\n")
예제 #12
0
def action(id, pw, booking_id):
    driver = Browser()
    driver.go_to(constants.URL)
    time.sleep(3)
    driver.click(tag='a', text='Log in')
    print('>>> Logging in')
    time.sleep(3)
    driver.type(id, into='Enter Member ID, barcode or email address')
    driver.type(pw, into='Enter password')
    driver.click(xpath=constants.LOGIN_BUTTON_PATH)
    time.sleep(10)

    if driver.exists(
            tag='span',
            text='Email address or Barcode or Member ID not recognized'):
        print(
            'ERROR: Unable to login (Email address or Barcode or Member ID not recognized)'
        )
        return

    location = driver.find_elements(
        id='js-search-location-default-club')[0].get_attribute('innerText')
    time.sleep(3)

    # Switch location
    if location != constants.LOCATION:
        print('>>> Switching locations')
        driver.click(tag='a', id='js-search-filter-change')
        driver.click(tag='section', id='section_clubs')
        # Switch to correct location
        driver.execute_script(
            'document.querySelector(\'[data-clubnumber="243"]\').click()')
        driver.click(id='js-filter-location-button-apply')
        time.sleep(3)

    print('>>> Booking...')
    driver.click(tag='label', classname='c-filter__label', text='Co-ed')
    time.sleep(3)
    driver.click(classname='js-unordered-list-button-mobile')
    # Select the newest day
    driver.click(tag='li', css_selector='[data-day="day-number-7"]')

    if driver.exists(tag='h5',
                     text='Open Workout',
                     xpath=constants.OPEN_WORKOUT_PATH):
        booking_id = booking_id + 1

    driver.click(xpath=constants.LAST_BOOKING_OPTIONS.replace(
        'li', 'li[' + str(booking_id) + ']'))

    if driver.errors:
        print('ERROR: Fully booked')
        return

    time.sleep(2)
    # Scroll to bottom of modal
    driver.execute_script('var element = document.getElementById("js-workout-booking-agreement-input"); ' \
            'element.scrollIntoView()')
    # Agreement
    driver.execute_script(
        'document.getElementById("js-workout-booking-agreement-input").click();'
    )
    time.sleep(2)
    driver.click(text='Confirm')
    print('>>> Booking confirmed')
    time.sleep(2)
    # Close confirmation dialog
    driver.click(xpath=constants.CLOSE_DIALOG_PATH)
    print('>>> Logging out')
    driver.click(tag='a', text='logout')
    print('>>> Finished')
예제 #13
0
#     def __init__(self):
#         self.driver = webdriver.Firefox()

#     def parse(self,response):
#             self.driver.get('https://tuoitre.vn/tim-kiem.htm?keywords=a')

#             while True:
#                 try:
#                     next = self.driver.find_element_by_xpath('//*[@class="btn-readmore"]')
#                     url = 'https://tuoitre.vn/tim-kiem.htm?keywords=a'
#                     yield Request(url,callback=self.parse2)
#                     next.click()
#                 except:
#                     break

#             self.driver.close()

#     def parse2(self,response):
#         print ('you are here!')

browser = Browser()
browser.go_to(
    'https://tuoitre.vn/thuy-tien-giai-trinh-178-ti-cuu-tro-mien-trung-2-vo-chong-ca-si-gop-them-gan-3-7-ti-20201123215443513.htm'
)
time.sleep(10)
print('hi')
comment = browser.find_elements(classname="article-title")
print('hi')
print(comment)
comment.text
print(comment)
예제 #14
0
파일: client.py 프로젝트: nekeal/tritest
class TribalClient:
    def __init__(self,
                 session_cookie,
                 world,
                 word_settings: WorldSettings = None):
        self.driver = Browser()
        self.world = world
        self._session_cookie = session_cookie
        self.barbarians = []
        self.available_troops = {key.value: 0 for key in Troops}

    def login(self):
        self.driver.go_to('https://plemiona.pl')
        self.driver.add_cookie({
            'name': 'pl_auth',
            'value': self._session_cookie
        })
        self.driver.refresh()
        self.driver.click(text=str(self.world))
        if self.driver.exists(id='popup_box_daily_bonus'):
            self.driver.click(classname='popup_box_close')

    def get_current_domain(self):
        uri = self.driver.get_current_url()
        parsed_uri = urlparse(uri)
        return f'{parsed_uri.scheme}://{parsed_uri.netloc}'

    def get_outgoings_attacks_from_place(self):
        self.go_to_place()
        outgoings_attacks_box = self.driver.driver.find_element_by_id(
            'commands_outgoings')
        attacked_villages_elements = outgoings_attacks_box.find_elements_by_class_name(
            'quickedit-label')

    @staticmethod
    def _replace_screen_in_url(url, screen_name: str) -> str:
        parsed_url = urlparse(url)
        parsed_query = parse_qs(parsed_url.query)
        parsed_query['screen'] = screen_name
        final_url = parsed_url._replace(
            query=urlencode(parsed_query, doseq=True)).geturl()
        return final_url

    def go_to_place(self):
        if 'screen=place' not in self.driver.get_current_url():
            self.driver.go_to(
                f'{self.get_current_domain()}/game.php?village=62967&screen=place'
            )

    def go_to_train_screen(self):
        if 'screen=train' not in self.driver.get_current_url():
            self.driver.go_to(
                f'{self.get_current_domain()}/game.php?village=62967&screen=train'
            )

    def go_to_main_screen(self):
        if 'screen=main' not in self.driver.get_current_url():
            self.driver.go_to(
                self._replace_screen_in_url(self.driver.get_current_url(),
                                            'main'))

    def slow_type(self, text, *args, **kwargs):
        text_input = self.driver.find_elements(*args, **kwargs)[0]
        text_input.clear()
        for letter in text:
            text_input.send_keys(letter)
            time.sleep(0.020)
            # self.driver.type(letter, *args, clear=False, **kwargs)

    def _extend_viallages_list(self):
        self.driver.driver.find_element_by_css_selector(
            '.village-item.village-more').click()

    def get_nearest_barbarians_villages(self, radius=10):
        # self.go_to_place()
        # self.driver.click(css_selector='input[value="village_name"]')  # nazwa wioski radio button
        self.slow_type('Wioska Barbarzyńska',
                       css_selector='#content_value .target-input-field')
        time.sleep(0.2)
        x = self.driver.driver.find_elements_by_class_name(
            'target-input-field')
        farthest_village_distance = 1
        villages = []
        # time.sleep(0.5)
        while farthest_village_distance < radius:
            time.sleep(0.1)
            villages = self.driver.driver.find_elements_by_css_selector(
                'div.target-select-autocomplete .village-item')[:-1]
            farthest_village_distance = parse_village_html(
                villages[-1]).distance
            self._extend_viallages_list()
        self.barbarians = []
        for village in villages:
            parsed_village = parse_village_html(village)
            if parsed_village.owner == 'Barbarzyńskie':
                self.barbarians.append(parsed_village)

    def get_troop_type_count_from_place(self, troop_type):
        unparsed_number = self.driver.driver.find_element_by_id(
            f'units_entry_all_{troop_type}').text
        return int(unparsed_number[1:-1])

    def get_troop_type_count_available_to_recruit(self, troop_type):
        self.go_to_train_screen()
        available_count_element = self.driver.driver.find_element_by_id(
            f'{troop_type.value}_0_a')
        return int(available_count_element.text[1:-1])

    def get_available_troops(self):
        for troop_type in Troops:
            self.available_troops[
                troop_type.value] = self.get_troop_type_count_from_place(
                    troop_type)
        return self.available_troops

    def get_available_resources(self) -> Resources:
        wood = int(self.driver.driver.find_element_by_id('wood').text)
        stone = int(self.driver.driver.find_element_by_id('stone').text)
        iron = int(self.driver.driver.find_element_by_id('iron').text)
        max_storage = int(
            self.driver.driver.find_element_by_id('storage').text)
        population = int(
            self.driver.driver.find_element_by_css_selector(
                'span#pop_current_label').text)
        max_population = int(
            self.driver.driver.find_element_by_css_selector(
                'span#pop_max_label').text)
        return VillageResources(wood, stone, iron, population, timedelta(0),
                                max_storage, max_population)

    def _fill_troop_form(self, troop_type, value):
        input_text = self.driver.driver.find_element_by_css_selector(
            f'#unit_input_{troop_type}')
        input_text.clear()
        input_text.send_keys(value)

    def fill_recruit_troop_form(self, troop_type, value):
        input_element = self.driver.driver.find_element_by_name(
            troop_type.value)
        input_element.clear()
        input_element.send_keys(str(value))

    def confirm_recruit(self):
        confirm_btn = self.driver.driver.find_element_by_class_name(
            'btn-recruit')
        confirm_btn.click()

    def _fill_target_village_cords(self, cords: Tuple[int, int]):
        target_input = self.driver.driver.find_element_by_class_name(
            'target-input-field')
        target_input.send_keys(f'{cords[0]}{cords[1]}')
        time.sleep(uniform(0.1, 0.2))

    def _confirm_attack(self):
        self.driver.driver.find_element_by_id('target_attack').click()
        time.sleep(uniform(0.1, 0.2))
        self.driver.driver.find_element_by_id('troop_confirm_go').click()

    def send_attack(self, target_cords: Tuple[int, int], troop_config: dict):
        self.go_to_place()
        self._fill_target_village_cords(target_cords)
        for troop_type, troop_count in troop_config.items():
            self._fill_troop_form(troop_type, troop_count)
        self._confirm_attack()

    def send_attack_to_nearest_villages(self,
                                        count=5,
                                        skip=0,
                                        light_chunk_count=5,
                                        axe_chunk_count=1):
        self.go_to_place()
        self.get_available_troops()
        count = light_chunk_count + axe_chunk_count
        light_chunk_size = int(self.available_troops[Troops.LIGHT.value] /
                               light_chunk_count)
        axe_chunk_size = int(self.available_troops[Troops.AXE.value] /
                             axe_chunk_count)

        for village in self.barbarians[skip:skip + count]:
            any_troops = False
            if light_chunk_count and light_chunk_size > 10:
                self._fill_troop_form(Troops.LIGHT, light_chunk_size)
                light_chunk_count -= 1
                any_troops = True
            elif axe_chunk_count and axe_chunk_size > 50:
                self._fill_troop_form(Troops.AXE, axe_chunk_size)
                axe_chunk_count -= 1
                any_troops = True
            if any_troops:
                self._fill_target_village_cords(village.cords)
                time.sleep(0.2)
                self._confirm_attack()
                time.sleep(0.2)

    def _get_build_row(self, building_name):
        return self.driver.driver.find_element_by_css_selector(
            f'tr#main_buildrow_{building_name}')

    def _get_build_orders_rows_for_building(self, building_name: str):
        return self.driver.driver.find_elements_by_class_name(
            f'buildorder_{building_name}')

    def _get_build_queue_rows(self):
        self.go_to_main_screen()
        return self.driver.driver.find_elements_by_css_selector(
            'tbody#buildqueue>tr.nodrag, tbody#buildqueue>.sortable_row')

    def get_build_queue_size(self):
        return len(self._get_build_queue_rows())

    def get_build_end_time(self):
        build_queue_rows = self._get_build_queue_rows()
        end_time = datetime.now()
        for build_row in build_queue_rows:
            time_string = build_row.find_element_by_css_selector('td')
            end_time += TimeHelper.parse_tribal_timedelta_format(time_string)
        return end_time

    def get_building_level(self, building_name) -> int:
        building_row = self._get_build_row(building_name)
        current_level_string = building_row.find_element_by_tag_name(
            'td').find_element_by_tag_name('span').text
        try:
            current_level = int(re.search("\d+", current_level_string).group())
        except AttributeError:
            current_level = 0
        build_order_row_for_building = self._get_build_orders_rows_for_building(
            building_name)
        return current_level + len(build_order_row_for_building)

    def build(self, build_queue: deque):
        for i in range(2 - self.get_build_queue_size()):
            if not build_queue:
                print('Pusta kolejka')
                return
            building_name = build_queue.popleft()
            building_row = self._get_build_row(building_name)
            try:
                build_inactive_displayed = building_row.find_element_by_css_selector(
                    'span.inactive').is_displayed()
            except NoSuchElementException:
                build_inactive_displayed = False
            if build_inactive_displayed:
                print(f"Currently you can't build {building_name}")
                build_queue.appendleft(building_name)
                return
            build_button = building_row.find_element_by_css_selector(
                'td.build_options a.btn-build')
            try:
                build_button.click()
                level = int(re.search(r'\d+', build_button.text).group())
                print(f'Built {building_name} at level {level}')
                time.sleep(0.1)
            except StaleElementReferenceException:
                build_queue.appendleft(building_name)

    def continous_attack(self, light_chunk_size=20):
        self.go_to_place()
        self.get_available_troops()

        while True:
            if self.get_troop_type_count_from_place(
                    Troops.LIGHT) >= light_chunk_size:
                village = random.choice(self.barbarians)
                self._fill_troop_form(Troops.LIGHT, light_chunk_size)
                time.sleep(0.2)
                self._fill_target_village_cords(village.cords)
                time.sleep(0.2)
                self._confirm_attack()
            else:
                time.sleep(0.2)
예제 #15
0
class WebbotManager:
    web = None
    _passwords = Passwords()

    def __init__(self, download_path=None):
        self.web = Browser(showWindow=True, downloadPath=download_path)
        self.web.maximize_window()

    def __del__(self):
        self.web.quit()

    def download_seis(self):
        """
        Navigates to the seis website, logs in, and downloads the seis summative export. Not the one for TOMS,
        the first one which provides us with more data like the case manager.
        """
        self.web.go_to("https://seis.org/reports/toms")
        self.web.type(self._passwords.seis_login_information['username'],
                      id="username")
        self.web.type(self._passwords.seis_login_information['password'],
                      id="password")
        self.web.click("Login")
        sleep(3)
        self.web.click(
            xpath='//*[@id="form"]/div/div/div/div/div[1]/div/div/button')
        sleep(30)
        self.web.click("XLSX", number=1)

    def cleanup_seis(self):
        """
        Deletes the SEIS report that was just downloaded.
        """
        self.web.click(classname='seis-icon-delete')
        self.web.click(xpath="/html/body/div[3]/div/div/div[3]/button[1]")

    def sign_in_to_caaspp(self):
        """
        Navigates to the TOMS system and logs in. TOMS thinks it's a new device logging in so it asks for a login
        code which it emails to me and the login manager grabs.
        """
        self.web.go_to("https://mytoms.ets.org/")
        self.web.type(self._passwords.caaspp_login_information['username'],
                      id="username")
        self.web.type(self._passwords.caaspp_login_information['password'],
                      id="password")
        self.web.click("Secure Logon")
        self.web.type(EmailManager().retrieve_login_code(), id="emailcode")
        self.web.click("Submit")
        self.web.click(xpath='//*[@id="roleOrgSelect"]/optgroup/option[2]')
        self.web.click(xpath='//*[@id="okButton"]')

    def upload_test_settings(self, filepath: str):
        self.web.go_to("https://mytoms.ets.org/mt/dt/uploadaccoms.htm")
        self.web.click("Next")
        self.web.type(filepath, xpath='//*[@id="uploadfilepath"]')
        self.web.click("Next")

    def upload_is_valid(self) -> bool:
        print(
            f"File is processing. Will check at {(datetime.now() + timedelta(0, 120)).strftime('%m/%d/%Y %I:%M:%S %p')}"
        )
        sleep(120)
        loops = 20
        while loops >= 0:
            elements = self.web.find_elements(tag='td')
            validation_data = {
                'datetime':
                datetime.strptime(elements[1].text, '%b %d, %Y, %I:%M %p'),
                'status':
                elements[3],  # .text
                'action':
                elements[4]
            }
            if validation_data['status'].text.startswith('Errors'):
                validation_data['action'].click()
                return False
            elif validation_data['status'].text.startswith('Validated'):
                validation_data['action'].click()
                return True
            else:
                print(
                    f"Still processing. Will re-try at {(datetime.now() + timedelta(0, 120)).strftime('%m/%d/%Y %I:%M:%S %p')}"
                )
                loops -= 1
                sleep(120)
                # Had initially used recursion but I didn't want to risk running into the stack loop limit.

        # If managed to get out of loop, report error.
        EmailManager().send_email(
            subject="TOMS Settings Upload Validation Failed Error",
            body=
            "Something went wrong with trying to validate the TOMS Settings Upload file in TOMS."
        )
        exit()
rewrite = False

if path.exists('antideps.pk1') and not rewrite:
    read = open('antideps.pk1', 'rb')
    antideps = pickle.load(read)
    read.close()

else:
    web = Browser()
    num_elem = 15
    scores = []
    for antidep in antideps.keys():
        web.go_to('google.com')
        web.type('reddit ' + antidep)
        web.press(web.Key.ENTER)
        links = min(num_elem, len(web.find_elements('reddit.com', tag='h3')))
        for link in range(1, links + 1):
            web.click('reddit.com', tag='h3', number=link)
            el = web.find_elements(tag='p')
            antideps[antidep] += list(map(lambda x: x.text, el))
            web.go_to('google.com')
            web.type('reddit ' + antidep)
            web.press(web.Key.ENTER)
    write = open('antideps.pk1', 'wb')
    pickle.dump(antideps, write)
    write.close()

sia = SIA()

scores = []
for antidep in antideps.keys():
예제 #17
0
def main():
	while True:
		web = Browser(showWindow = pencere_acilsin_mi)
		try:
			m1 = random.randint(20,500)
			m2 = random.randint(-200,700)
			m3 = random.randint(40,900)
			web.set_page_load_timeout(60)
			web.go_to(site)
			if web.exists(kelime):
				sleep(random.randint(20,50))
				print("anasayfa")
				web.scrolly(m1) 
				web.scrolly(m2) 
				web.scrolly(m3)
				try:
					a = []
					a = web.find_elements(tag='a')
					sec = random.choice(a)
					sec.click()
					print(web.get_title())
					acik = web.get_total_tabs()
					if acik>1:
						web.switch_to_tab(2)
					sleep(random.randint(20,50))
					web.scrolly(m1) 
					web.scrolly(m2) 
					web.scrolly(m3)
					try:
						a = []
						a = web.find_elements(tag='a')
						sec = random.choice(a)
						sec.click()
						acik1 = web.get_total_tabs()
						if acik1>1:
							web.switch_to_tab(acik1)
						sleep(random.randint(20,50))
						print(web.get_title())
						web.scrolly(m1) 
						web.scrolly(m2) 
						web.scrolly(m3)
						try:
							a = []
							a = web.find_elements(tag='a')
							sec = random.choice(a)
							sec.click()
							acik2 = web.get_total_tabs()
							if acik2>1:
								web.switch_to_tab(acik2)
							sleep(random.randint(20,50))
							print(web.get_title())
							web.scrolly(m1) 
							web.scrolly(m2) 
							web.scrolly(m3)
							try:
								a = []
								a = web.find_elements(tag='a')
								sec = random.choice(a)
								sec.click()
								acik3 = web.get_total_tabs()
								if acik3>1:
									web.switch_to_tab(acik3)
								sleep(random.randint(20,50))
								print(web.get_title())
								web.scrolly(m1) 
								web.scrolly(m2) 
								web.scrolly(m3)
								try:
									a = []
									a = web.find_elements(tag='a')
									sec = random.choice(a)
									sec.click()
									acik4 = web.get_total_tabs()
									if acik4>1:
										web.switch_to_tab(acik4)
									sleep(random.randint(20,50))
									print(web.get_title())
									web.scrolly(m1) 
									web.scrolly(m2) 
									web.scrolly(m3)
									try:
										a = []
										a = web.find_elements(tag='a')
										sec = random.choice(a)
										sec.click()
										acik5 = web.get_total_tabs()
										if acik5>1:
											web.switch_to_tab(acik5)
										sleep(random.randint(20,50))
										print(web.get_title())
										web.scrolly(m1) 
										web.scrolly(m2) 
										web.scrolly(m3)
										try:
											a = []
											a = web.find_elements(tag='a')
											sec = random.choice(a)
											sec.click()
											acik6 = web.get_total_tabs()
											if acik6>1:
												web.switch_to_tab(acik6)
											sleep(random.randint(20,50))
											print(web.get_title())
											web.scrolly(m1) 
											web.scrolly(m2) 
											web.scrolly(m3)
											try:
												a = []
												a = web.find_elements(tag='a')
												sec = random.choice(a)
												sec.click()
												acik7 = web.get_total_tabs()
												if acik7>1:
													web.switch_to_tab(acik7)
												sleep(random.randint(20,50))
												print(web.get_title())
												web.scrolly(m1) 
												web.scrolly(m2) 
												web.scrolly(m3)
												web.quit()
											except:
												web.quit()
										except:
											web.quit()
									except:
										web.quit()
								except:
									web.quit()
							except:
								web.quit()
						except:
							web.quit()
					except:
						web.quit()	
				except:
					web.quit()	
			else:
				web.quit()
		except:
			web.quit()
예제 #18
0
import pandas as pd
from datetime import date

def convert_MBtoGB(mb):
    return int(float(mb)/1024)

web = Browser()
web.go_to('??.in')
web.type('', id='DUser')
web.type('', id='Pwd')
web.press(web.Key.ENTER)
print(web.get_current_url())

web.go_to('??.in/goToForm?formId=CUP001')

used_data_mb = web.find_elements(id='totalOctet')[0].text
rem_data_mb = web.find_elements(id='totalOctets')[0].text
today = date.today()

print(used_data_mb)
print(rem_data_mb)
print(today)

# # used_data_mb = '35100.55'
# # rem_data_mb = '5000.45'
used_data = convert_MBtoGB(used_data_mb)
rem_data = convert_MBtoGB(rem_data_mb)

web.go_to('??.in/signout')

# # log_file_df = pd.read_csv("log.csv")