1

Estoy buscando armar alguna funcion con for in para recorrer mi diccionario. Explico un poco el codigo que tengo aca, uso selenium. Dentro de Def Name() en la variable nametag, llamo a "NameTag" de mi diccionario. Asi sucesivamente con todos los datos de mi diccionario de MW $1.5. Ahora bien, por ahora mi programa cumple todo con MW $ 1.5, quiero que una vez que termino vuelva a arrancar con la siguiente fila del diccionario, MW $ 2.5 y haga lo mismo. Vale aclarar que los pasos que necesito que se repitan con los valores del dic son desde def clone()

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome('/Users/Martin/Desktop/chromedriver')
timeout = 30
driver.get("https://onevideo.aol.com/#/")
diccionario = {"inventorysources":{"Nametag": "MW $ 1.5 |","Floor_rate": "1.5","Rate": "2"},
                                  "Nametag": "MW $ 2.5 |","Floor_rate": "2.5","Rate": "3.25"}


def main():
    login()
    clone()
    Name()
    Rate()
    Floor()
    Download()


def login():
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, "input.ng-valid:nth-child(1)"))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")

    username = driver.find_element_by_css_selector("input.ng-valid:nth-child(1)")
    username.send_keys("user")
    driver.find_element_by_css_selector("button.btn:nth-child(2)").click()
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, "div.group-field-block:nth-child(2) > input:nth-child(2)"))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")

    password = driver.find_element_by_css_selector("div.group-field-block:nth-child(2) > input:nth-child(2)")
    password.send_keys("pass")
    driver.find_element_by_css_selector(".button").click()
    element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'h1.ng-scope > span:nth-child(1)')))


def clone():
#Clonar
    url = driver.get("https://onevideo.aol.com/#/inventorysources")
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, "div.ngRow:nth-child(1) > div:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > adap-options-menu:nth-child(1) > div:nth-child(1) > button:nth-child(2)"))
        WebDriverWait(driver, timeout).until(element_present)

    except TimeoutException:
        print ("Timed out waiting for page to load")
    driver.find_element_by_css_selector('div.ngRow:nth-child(1) > div:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > adap-options-menu:nth-child(1) > div:nth-child(1) > button:nth-child(2)').click()
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, "div.ngRow:nth-child(1) > div:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > adap-options-menu:nth-child(1) > div:nth-child(1) > button:nth-child(2)"))
        WebDriverWait(driver, timeout).until(element_present)

    except TimeoutException:
        print ("Timed out waiting for page to load")    
    driver.find_element_by_css_selector('.open > ul:nth-child(5) > li:nth-child(3) > a:nth-child(1)').click()


def Name():
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, 'div.margin-top-medium > input:nth-child(1)'))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")
    name = driver.find_element_by_css_selector('div.margin-top-medium > input:nth-child(1)')
    name.clear()
    fecha = time.strftime("%d-%m-%y")
    nametag = name.send_keys(str(diccionario["inventorysources"]["Nametag"]), fecha)


def Rate():
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, '.span9 > div:nth-child(1) > form:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > span:nth-child(1) > adap-input:nth-child(1) > span:nth-child(1) > input:nth-child(2)'))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")
    Rate = driver.find_element_by_css_selector('.span9 > div:nth-child(1) > form:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > span:nth-child(1) > adap-input:nth-child(1) > span:nth-child(1) > input:nth-child(2)')
    Rate.clear()
    Rate.send_keys(str(diccionario["inventorysources"]["Floor_rate"]))


def Floor():
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, '.span9 > div:nth-child(1) > form:nth-child(1) > div:nth-child(12) > div:nth-child(2) > adap-input:nth-child(1) > span:nth-child(1) > input:nth-child(1)'))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")
    Floor = driver.find_element_by_css_selector('.span9 > div:nth-child(1) > form:nth-child(1) > div:nth-child(12) > div:nth-child(2) > adap-input:nth-child(1) > span:nth-child(1) > input:nth-child(1)')
    Floor.clear()
    Floor.send_keys(str(diccionario["inventorysources"]["Rate"]))


def Save():
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, ".bs-docs-social-buttons > li:nth-child(2) > button:nth-child(1)"))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")
    Save = driver.find_element_by_css_selector(".bs-docs-social-buttons > li:nth-child(2) > button:nth-child(1)").click()
    element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'h1.ng-scope > span:nth-child(1)')))


if __name__ == 'main':
    main()

1 respuesta 1

1

Antes de todo dos correcciones:

  • El diccionario no es correcto tal y como está (sobreescribes las claves), debería ser así en todo caso:

    diccionario = {"inventorysources":({"Nametag": "MW $ 1.5 |", "Floor_rate": "1.5", "Rate": "2"}, 
                                       {"Nametag": "MW $ 2.5 |", "Floor_rate": "2.5", "Rate": "3.25"})
                  }
    
  • La línea if __name__ == 'main': es incorrecta, debe ser if __name__ == '__main__':.

Por otro lado, no se si se debe ejecutar en orden o no importa este detalle. Un diccionario no mantiene el orden de sus items, es decir, no tienes ninguna seguridad de que primero se ejecute "MW $ 1.5 |", luego "MW $ 2.5 |", etc. Si necesitas mantener el orden usa collections.OrderectDict.


Si he comprendido lo que quieres, puedes hacer que en tu main se itere sobre los valores de diccionario["inventorysources"] y llamar a cada función con el valor que necesita.

Para ello haz que cada función acepte el argumento que necesita. Sería algo así:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome('/Users/Martin/Desktop/chromedriver')
timeout = 30
driver.get("https://onevideo.aol.com/#/")

diccionario = {"inventorysources":({"Nametag": "MW $ 1.5 |","Floor_rate": "1.5","Rate": "2"}, 
                                   {"Nametag": "MW $ 2.5 |","Floor_rate": "2.5","Rate": "3.25"})
              }

def main():
    login()

    for inv_source in diccionario["inventorysources"]:
        clone()
        Name(inv_source["Nametag"])
        Rate(inv_source["Rate"])
        Floor(inv_source["Floor_rate"])
        Download()


def login():
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, "input.ng-valid:nth-child(1)"))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")

    username = driver.find_element_by_css_selector("input.ng-valid:nth-child(1)")
    username.send_keys("user")
    driver.find_element_by_css_selector("button.btn:nth-child(2)").click()
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, "div.group-field-block:nth-child(2) > input:nth-child(2)"))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")

    password = driver.find_element_by_css_selector("div.group-field-block:nth-child(2) > input:nth-child(2)")
    password.send_keys("pass")
    driver.find_element_by_css_selector(".button").click()
    element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'h1.ng-scope > span:nth-child(1)')))


def clone():
#Clonar
    url = driver.get("https://onevideo.aol.com/#/inventorysources")
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, "div.ngRow:nth-child(1) > div:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > adap-options-menu:nth-child(1) > div:nth-child(1) > button:nth-child(2)"))
        WebDriverWait(driver, timeout).until(element_present)

    except TimeoutException:
        print ("Timed out waiting for page to load")
    driver.find_element_by_css_selector('div.ngRow:nth-child(1) > div:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > adap-options-menu:nth-child(1) > div:nth-child(1) > button:nth-child(2)').click()
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, "div.ngRow:nth-child(1) > div:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > adap-options-menu:nth-child(1) > div:nth-child(1) > button:nth-child(2)"))
        WebDriverWait(driver, timeout).until(element_present)

    except TimeoutException:
        print ("Timed out waiting for page to load")    
    driver.find_element_by_css_selector('.open > ul:nth-child(5) > li:nth-child(3) > a:nth-child(1)').click()


def Name(nametag):
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, 'div.margin-top-medium > input:nth-child(1)'))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")
    name = driver.find_element_by_css_selector('div.margin-top-medium > input:nth-child(1)')
    name.clear()
    fecha = time.strftime("%d-%m-%y")
    nametag = name.send_keys(nametag, fecha)


def Rate(rate):
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, '.span9 > div:nth-child(1) > form:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > span:nth-child(1) > adap-input:nth-child(1) > span:nth-child(1) > input:nth-child(2)'))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")
    Rate = driver.find_element_by_css_selector('.span9 > div:nth-child(1) > form:nth-child(1) > div:nth-child(9) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > span:nth-child(1) > adap-input:nth-child(1) > span:nth-child(1) > input:nth-child(2)')
    Rate.clear()
    Rate.send_keys(rate)


def Floor(floor_rate):
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, '.span9 > div:nth-child(1) > form:nth-child(1) > div:nth-child(12) > div:nth-child(2) > adap-input:nth-child(1) > span:nth-child(1) > input:nth-child(1)'))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")
    Floor = driver.find_element_by_css_selector('.span9 > div:nth-child(1) > form:nth-child(1) > div:nth-child(12) > div:nth-child(2) > adap-input:nth-child(1) > span:nth-child(1) > input:nth-child(1)')
    Floor.clear()
    Floor.send_keys(floor_rate)


def Save():
    try:
        element_present = EC.presence_of_element_located((By.CSS_SELECTOR, ".bs-docs-social-buttons > li:nth-child(2) > button:nth-child(1)"))
        WebDriverWait(driver, timeout).until(element_present)
    except TimeoutException:
        print ("Timed out waiting for page to load")
    Save = driver.find_element_by_css_selector(".bs-docs-social-buttons > li:nth-child(2) > button:nth-child(1)").click()
    element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'h1.ng-scope > span:nth-child(1)')))


if __name__ == '__main__':
    main()
8
  • No pude hacerlo funcionar. Partiendo de la base que si pongo def no me corren las funciones, pero si cambio def por class si. El problema es que cuando tenga def con parametros como name si le tengo que poner class no puedo correrla Commented el 23 oct. 2017 a las 0:53
  • solo me funciona con class en vez de def. No me da ningun error, solo que no las ejecuta. Solo corre todo lo que esta por fuera de las funciones como abrir el driver e introducir la url del login Commented el 23 oct. 2017 a las 1:00
  • @MartinBouhier me acabo de dar cuenta pero if __name__ == 'main': es incorrecto, es if __name__ == '__main__':
    – FJSevilla
    Commented el 23 oct. 2017 a las 1:02
  • Ahora las ejecuta pero me salta este error: Name(inv_source["Nametag"]) TypeError: string indices must be integers, not str Commented el 23 oct. 2017 a las 1:06
  • ahi funciono aunque una vez despues que se guardo todo no vuelve a arrancar la funcion clone como necesito, lo cual me genera un error de time.out. Tengo el codigo exactamente como me lo mandaste vos actualizado y corregido Commented el 23 oct. 2017 a las 1:28

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.