pythonselenium-webdrivertkinterpath

Calling variable path from tkinter


I'm running a code in Python where it is divided into 2 parts, the first is a function to perform a webscrap on a page and the second to open an interface using tkinter for the user to choose a folder where the information will be saved. The problem is that I'm not able to pass the path that the user selected to my webscrapping code. Could you help me with this?

import tkinter
from tkinter import messagebox,ttk
from tkinter.filedialog import askdirectory
from tkinter.filedialog import FileDialog

######################################
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.common.exceptions import NoSuchElementException
import time
import IntegracaoRestTotvs #importa a funcao de integracao
import ConectaFTP #importa funcao de conexão com o ftp
import os

def geraarquivos():
    #função de integração
    x = IntegracaoRestTotvs.chamaapi()  # Chama a função
    if x:  # Verifica se a função retornou algo
        for item in x:
            matricula = item['matricula']  # Pega a matrícula
            nome = item['nome']  # Pega o nome
            print(f"Matrícula: {matricula}, Nome: {nome}")  # Exibe matrícula e nome
            #print(matricula)  # Imprime cada matrícula
            #print(nome)
            options = webdriver.ChromeOptions()
            options.add_argument("start-maximized") #
            options.add_experimental_option("excludeSwitches", ["enable-automation"])
            options.add_experimental_option('useAutomationExtension', False)
            options.add_experimental_option("detach", True)
            # download
            options.add_experimental_option('prefs', {
            "download.default_directory": "C:\\Users\\Lenovo NtBk2\\Downloads\\pdfs", #Change default directory for downloads
            #"download.prompt_for_download": False, #To auto download the file
            #"download.directory_upgrade": True,
            "plugins.always_open_pdf_externally": True #It will not show PDF directly in chrome 
            })

            driver = webdriver.Chrome(options=options)
            driver.get("xxxxx")

           
            WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name^='a-'][src^='https://www.google.com/recaptcha/api2/anchor?']")))
            WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[@id='recaptcha-anchor']"))).click()
            driver.switch_to.default_content()

            search = driver.find_element("name","inscricao")
            search.send_keys(matricula)
            search.send_keys(Keys.TAB)
            time.sleep(5)

            try:
                envia = driver.find_element(By.XPATH, "//button[text()='Emitir']")
                envia.click()
                time.sleep(5)
                t = driver.find_element(By.XPATH, "(//*[name()='path'][@fill='currentColor'])[18]")
                time.sleep(2)
                t.click()  
                time.sleep(5)
                driver.quit()
                os.rename('C:\\Users\\Lenovo NtBk2\\Downloads\\pdfs\\Documento de Arrecadação Municipal de Taxa de IPTU.pdf', "C:\\Users\\Lenovo NtBk2\\Downloads\\pdfs\\"+nome+".pdf")
            except:
                print("boleto já gerado!")
                driver.quit()
    ConectaFTP.conectaftp()


lista =["emp1", "outros"]
caminho = ""
root=tkinter.Tk()
root.geometry('400x200')
root.title("Importação Boletos")
empreendimento_label=tkinter.Label(root,text="Seleção de Empreendimento:")
empreendimento_label.pack(anchor=tkinter.W,padx=10)
empreendimento_dropdown = ttk.Combobox(root,values=lista)
empreendimento_dropdown.pack(anchor=tkinter.W,padx=10)



def Selecione_Arquivo():
    caminho = askdirectory()
    pasta_label.config(text=caminho)


botao_pasta = ttk.Button(root,text="Selecione a Pasta",command=Selecione_Arquivo)
botao_pasta.place(x=10,y=50)

pasta_label=tkinter.Label(root,text=caminho)
pasta_label.pack(anchor=tkinter.W,padx=10,pady=35)


botao_executa = ttk.Button(root, text="Executar",command= lambda: geraarquivos())
botao_executa.place(x=10,y=100)



root.mainloop()

For example, I need the path returned on line 84 to be applied on lines 36 and 64

I tried generating new functions to store the variables and change the order of the fields


Solution

  • Simple answer based on the code given? Just add a default parameter to your geraarquivos function and pass the path to the lambda your using for the button command - lambda: geraarquivos(pasta_label.cget('text')).