Beispiel #1
0
 def keyboard_enter(self, selector):
     """
     模拟键盘点击回车键
     :param selector:
     :return:
     """
     self._web_driver_wait(selector).send_keys(Keys().ENTER)
Beispiel #2
0
    def get_app_id(self):

        log_in_mail, log_in_pass = self.enter_account_credentials()

        chrome_options = Options()
        chrome_options.add_argument("--headless") # web browser without GUI

        driver = webdriver.Chrome(options=chrome_options)
        driver.get("https://openexchangerates.org/account/app-ids")
       
        email_in = driver.find_element_by_name('email')
        email_in.send_keys(log_in_mail)
        time.sleep(2)

        pass_in = driver.find_element_by_name('pwd')
        pass_in.send_keys(log_in_pass)

        time.sleep(1)

        keys = Keys() 
        pass_in.send_keys(keys.RETURN) 
        time.sleep(1)

        data = driver.page_source

        soup = BeautifulSoup(data, 'html.parser')

        locator = 'input#app-id-126408'
        app_id = soup.select_one(locator).attrs['value']

        return app_id
def group_members_page(browser, group_url):
    actions = webdriver.ActionChains(browser)
    browser.get(group_url)

    keys = Keys()
    actions.send_keys(keys.ESCAPE)
    actions.perform()
    def create_bid(self):
        print('Creating bid')
        bid_input = self.browser.find_element_by_xpath(
            '//input[@name="ask-amount"]')
        bid_input.send_keys(self.bid_value)

        try:
            warning_text = self.browser.find_element_by_class_name(
                'warning-text')
            warning_text = warning_text.text
            min_bid = warning_text[-3:]
            if min_bid[0] == '$':
                min_bid = min_bid[1:]

            self.bid_value = int(min_bid)
            bid_input.send_keys(
                Keys.chord(Keys.CONTROL, "a"), str(self.bid_value))
        except:
            pass

        review_btn = self.browser.find_element_by_class_name('button-green')
        review_btn.click()

        confirm_btn = self.browser.find_element_by_css_selector(
            constants.BID_CONFIRM_BUTTON_CSS_SELECTOR)
        confirm_btn.click()
Beispiel #5
0
def transform_key_string(key_string):
    key_string = key_string.upper().replace(' ', '_')
    if key_string == 'BACKSPACE':
        key_string = 'BACK_SPACE'
    elif key_string == 'SPACEBAR':
        key_string = 'SPACE'
    key = Keys.__getattribute__(Keys, key_string)
    return key
Beispiel #6
0
def transform_key_string(key_string):
    key_string = key_string.upper().replace(' ', '_')
    if key_string == 'BACKSPACE':
        key_string = 'BACK_SPACE'
    elif key_string == 'SPACEBAR':
        key_string = 'SPACE'
    key = Keys.__getattribute__(Keys, key_string)
    return key
def capture_gslide(chromedriver_path, gslide_url, max_page_no, save_folder=''):
    """ take screenshots of Google Slide
        max_page_no: int
    """
    # avoid SessionNotCreatedException
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.implicitly_wait(10)
    driver.get(gslide_url)
    time.sleep(3)

    actions = ActionChains(driver)
    actions.send_keys(Keys.END)
    actions.perform()
    time.sleep(3)

    # TODO:
    # get the number of slides ← different btwn each slide
    # contents = driver.find_elements_by_xpath('.//*[@id="filmstrip"]')
    # lst = [i.text for i in contents][0].split('\n')
    # lst = [int(i) for i in lst if re.match(r'[0-9]+', i)]
    # max_page_no = max(lst)
    # print('the number of slides: ', max_page_no)
    # time.sleep(3)

    # click on Present button and start Present from 1st slide
    # present_pulldown =  driver.find_element_by_xpath('.//*[@id="punch-start-presentation-right"]')
    # present_pulldown.click()
    # time.sleep(3)

    # start the presentation
    keys = Keys()
    actions = ActionChains(driver)
    actions.send_keys(keys.COMMAND + keys.SHIFT + keys.ENTER)
    actions.key_down(keys.SHIFT).key_down(keys.COMMAND).send_keys(keys.ENTER)
    actions.perform()
    time.sleep(8)

    # move to next page until the end
    # pressing PAGE_DOWN or ENTER seems not to work
    actions = ActionChains(driver)
    actions.click()
    counter = 1
    while counter <= int(max_page_no):
        fname = '{}.png'.format(str(counter).zfill(2))
        save_dir = os.path.join(save_folder, fname)
        driver.save_screenshot(save_dir)
        print('Page ' + str(counter) + ' was captured.')
        actions.perform()
        counter += 1
        time.sleep(2)


    print('DONE')
Beispiel #8
0
  def _fill_text_box(self, data_field, page):
    
    print data_field.tag_name, data_field.get_attribute('id'), "sending keys"
    if data_field.is_displayed()==True: #only sends keys to visible text boxes

      if 'autocomplete' in data_field.get_attribute('class'): #autocomplete text boxes
        k = Keys() #used for sending special keys

        if 'degree' in data_field.get_attribute('id'):
          data_field.send_keys('Mat')
        else:
          data_field.send_keys('Mar')
      
        data_field.send_keys(k.ARROW_DOWN) #goes down to first drowdown option
        
        try:
          wait_element = page.ip.is_element_clickable_by_xpath("//li[contains(@class, 'autocomplete')]") #waits for option to load
          highlighted_element = page.driver.find_element_by_xpath("//li[contains(@class, 'autocomplete')]")
          highlighted_element.click() #clicks option
        except Exception, e:
          #if 'Math' doesnt trigger dropdown then 'Ma' is tried
          data_field.clear()
          data_field.send_keys('Ma')
          data_field.send_keys(k.ARROW_DOWN) #goes down to first drowdown option
          wait_element = page.ip.is_element_clickable_by_xpath("//li[contains(@class, 'autocomplete')]") #waits for option to load
          highlighted_element = page.driver.find_element_by_xpath("//li[contains(@class, 'autocomplete')]")
          highlighted_element.click() #clicks option

      elif data_field.get_attribute('autocomplete')=='off': #special dropdown box on payment screen
        k = Keys()
        
        data_field.send_keys('Afghanistan') #did not choose U.S. because extra 'State' box changes
        data_field.send_keys(k.ENTER)
      else:
        try:
          data_field.clear()
          info = self.fake_info.fill_valid_value(data_field)
          data_field.send_keys(info)
        except Exception, e:
          pass
Beispiel #9
0
    def test_home(self):
        self.get("/")
        assert "QStode" in self.s.page_source

        search_box = self.s.find_element_by_id("query")
        if search_box:
            # select all in the field
            # https://stackoverflow.com/questions/3249583/selenium-webdriver-i-want-to-overwrite-value-in-field-instead-of-appending-to-i/3254152
            search_box.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55")
            search_box.send_keys("suca")
            search_box.send_keys(Keys.RETURN)
            assert "No matching bookmark was found." in self.s.page_source
        else:
            raise RuntimeError("search_box not found")
Beispiel #10
0
def getFollow(username,follwing=True):
    if(follwing):
        followNumCss = "li._bnq48:nth-child(2) > a:nth-child(1) > span:nth-child(1)"
        followButton = "li._bnq48:nth-child(2) > a:nth-child(1)"
    else:
        followNumCss = "li._bnq48:nth-child(3) > a:nth-child(1) > span:nth-child(1)"
        followButton = "li._bnq48:nth-child(3) > a:nth-child(1)"
    driver.get("https://www.instagram.com/"+username)
    followingNum = driver.find_element_by_css_selector(followNumCss).get_attribute("innerHTML")
    followingButton = driver.find_element_by_css_selector(followButton)
    followingButton.click()
    sleep(sleepTime)
    followingList = []
    downKey = Keys()
    for i in range(1, int(followingNum)+1):
        #li._6e4x5:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > a:nth-child(1)
        followingUsername = driver.find_element_by_css_selector('li._6e4x5:nth-child('+str(i)+') > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > a:nth-child(1)')
        followingList.append(followingUsername.get_attribute("innerHTML"))
        followingUsername.send_keys(downKey.DOWN)
        sleep(0.250)
    return sorted(followingList)
Beispiel #11
0
def on_report(report, conn):
    keys = list()
    updates = list()

    for joystick in report.joystick:
        if abs(joystick.info.mean) > threshold:
            d = joy_to_dir[joystick.axis][copysign(1, joystick.info.mean)]
            keys.append(d)
            update = progress(
                "JOYSTICK",
                joystick.axis,
                min(0.999, abs(joystick.info.mean / threshold))
            )
        else:
            update = progress("JOYSTICK", joystick.axis, 0)
            updates.append(update)

    for update in updates:
        conn.send(update)

    for key in keys:
        print("SENDING KEYPRESS:", key)
        game_elem.send_keys(Keys().__getattribute__(key))
    def send_especific_keys(self, element, key):
        if key == 'Enter':
            Functions.get_elements(self, element).send_keys(Keys.ENTER)

        elif key == 'Tab':
            Functions.get_elements(self, element).send_keys(Keys.TAB)

        elif key == 'Space':
            Functions.get_elements(self, element).send_keys(Keys.SPACE)

        elif key == 'Del':
            Functions.get_elements(self, element).send_keys(
                Keys.chord(Keys.CONTROL, "a", Keys.DELETE))

        elif key == 'Back':

            lenText = Functions.get_elements(self, element).text

            while lenText == 0:
                Functions.get_elements(self,
                                       element).send_keys(Keys.BACK_SPACE)
                lenText = lenText - 1

        time.sleep(3)
Beispiel #13
0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
import os
from bs4 import BeautifulSoup
import urllib
import requests


class InstaBot:
    def __init__(self):
        self.bot = webdriver.Firefox()

    def login(self):
        bot = self.bot
        bot.get('https://dms.jaipur.manipal.edu/loginForm.aspx')
        time.sleep(5)
        capcha = bot.find_element_by_id('imgCaptcha')
        src = capcha.get_attribute("src")
        bot.get(src)
        bot.save_screenshot("capcha.png")


harvey = InstaBot()
harvey.login()
key = Keys()
Beispiel #14
0
# coding=utf-8
# author:dn_eric(qq:2384363842)
# 动脑学院pythonVip课程
# 创建于: 2018/1/31 15:17
"""
Keys()类提供了键盘上几乎所有按键的方法。 前面了解到, send_keys()方法可以用来模拟键盘输入,
除此 之外, 我们还可以用它来输入键盘上的按键, 甚至是组合键, 如 Ctrl+A、 Ctrl+C 等。
"""
import time
from selenium import webdriver
# 引入 Keys 模块
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")

# 输入框输入内容
driver.find_element_by_id("kw").send_keys("动脑学员")
time.sleep(3)
# 删除输入错误的一个员
driver.find_element_by_id("kw").send_keys(Keys.BACK_SPACE)
time.sleep(3)

# 输入“院”
driver.find_element_by_id("kw").send_keys("院")
time.sleep(3)
# ctrl+a 全选输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'a')
time.sleep(3)
# ctrl+x 剪切输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'x')
Beispiel #15
0
import selenium
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.interaction import KEY
from selenium.webdriver.common.keys import Keys

driver = selenium.webdriver.Chrome()
driver.switch_to.window()
driver.forward()
action = ActionChains(driver).key_down(Keys.CONTROL())

 def page_down_(self):
     k = Keys()
     k.PAGE_DOWN
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import random
import time
import sys
import datetime

options = Options()
# options.add_argument('--headless')
# options.add_argument('--no-sandbox')
# options.add_argument('--disable-gpu')


keys = Keys()
x = datetime.datetime.now()
class InstagramBot:
	def __init__(self, username, password,):
		self.username = username
		self.password = password
		self.driver = webdriver.Chrome(options = options, executable_path='/Users/Perm/Downloads/Chromedriver')

	def closeBrowser(self):
		self.driver.close()

	def login(self):
		driver = self.driver
		driver.get("https://www.instagram.com/")
		driver.get_screenshot_as_file("insta.png")	
		print("Headless Chrome Initialized")
Beispiel #18
0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()

sign = input("Please enter your email address: ")

password = getpass.getpass("Enter your password")

driver.get("https://www.office.com/")

find_element_by_xpath(
    '//*[@id="hero-banner-sign-back-in-to-office-365-link"]').click()

find_element_by_xpath('//*[@id="i1668"]').click()

find_element_by_xpath('//*[@id="otherTileText"]').cick()

find_element_by_xpath('//*[@id="i0116"]').sendKeys(
    Keys.HOME, Keys.chord(Keys.SHIFT, Keys.END), sign)

find_element_by_xpath('//*[@id="idSIButton9"]').click()

find_element_by_xpath('//*[@id="i0118"]').sendKeys(
    Keys.HOME, Keys.chord(Keys.SHIFT, Keys.END), password)

break
Beispiel #19
0
 def keys(self):
     return Keys()
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = None

try:
    cpath = '/usr/local/bin/chromedriver'
    driver = webdriver.Chrome(cpath)
    driver.get('https://google.com')
    
    search_element = driver.find_element_by_name('q')
    
    search_element.send_keys('blue heeler puppies')
    search_element.send_keys(Keys().RETURN)
    
    driver.save_screenshot('heelers.png')

finally:
    if driver is not None:
        driver.close()
Beispiel #21
0
def vehicle_enum(req):
    q = req

    #image = Image.open('download.jpeg', mode='r')
    #image_to_text = pytesseract.image_to_string(image, lang='eng')
    #text = ''
    #text=image_to_text
    #text1=str(text)
    #q=text1
    class Bot:
        def __init__(self, number):
            self.number = number
            self.bot = webdriver.Firefox()

        def login(self):
            bot = self.bot

            bot.get('https://rtovehicle.info/index.php')
            time.sleep(2)

            search = bot.find_element_by_id('vehiclenum')
            search.send_keys(self.number)

            clicker = bot.find_element_by_id('searchB')
            clicker.click()

            time.sleep(3)
            bot.execute_script("window.scrollTo(0, 400)")
            bot.save_screenshot("rto.png")

        def img_text(self):
            pytesseract.pytesseract.tesseract_cmd = r"tesseract"
            image = Image.open('rto.png')
            image_to_text = pytesseract.image_to_string(image, lang='eng')
            text = ''
            text = image_to_text
            text1 = str(text)
            #print(text)
            D = ModernStructures.makedf(text1)
            #print(D)
            global s
            s = D
            os.system("pkill -f firefox")

    quantin = Bot(q)
    quantin.login()
    key = Keys()
    quantin.img_text()

    from sqlalchemy import create_engine

    import pymysql
    import numpy as np
    import pandas as pd
    tableName = "RC"

    dataFrame = s
    dataFrame = dataFrame.T
    dataFrame.columns = [
        'Name', 'Vehicle_name', 'Regestration_no', 'Date', 'Time'
    ]
    dataFrame.drop(labels=None,
                   axis=0,
                   index=0,
                   columns=None,
                   level=None,
                   inplace=True,
                   errors='raise')
    dataFrame.reset_index(drop=True, inplace=True)
    dataFrame.to_string(index=False)
    print(dataFrame)

    sqlEngine = create_engine(
        'mysql+pymysql://root:[email protected]/final_year',
        pool_recycle=3600)

    dbConnection = sqlEngine.connect()

    try:

        frame = dataFrame.to_sql(tableName,
                                 dbConnection,
                                 index=False,
                                 if_exists='append')

    except ValueError as vx:

        print(vx)

    except Exception as ex:

        print(ex)

    else:

        print("Inserted data to %s Successfully." % tableName)

    finally:

        dbConnection.close()