You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将Tkinter选择的文件夹路径传入爬虫函数?

解决Tkinter选择路径传递给Selenium爬虫的问题

问题说明

代码分为两部分:geraarquivos()实现网页爬取与文件下载重命名,Tkinter界面提供文件夹选择功能。当前无法将用户选择的路径传递到爬虫逻辑中,需将选择的路径应用到两处:

  • Chrome浏览器的下载路径配置(原代码第36行)
  • 下载后的文件重命名目标路径(原代码第64行)

解决方案

问题根源在于:

  1. Selecione_Arquivo()中定义的caminho是局部变量,无法修改全局作用域的caminho变量
  2. geraarquivos()未接收路径参数,无法获取用户选择的路径

修改步骤:

  • 在Selecione_Arquivo()中通过global关键字声明操作全局变量caminho
  • 修改geraarquivos(),添加download_path参数,在函数内使用该参数配置下载路径和重命名文件
  • 点击执行按钮时,传递全局变量caminho给geraarquivos(),并增加路径非空判断

修改后的完整代码

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

# 添加download_path参数
def geraarquivos(download_path):
    # 先判断路径是否有效
    if not download_path:
        messagebox.showwarning("警告", "请先选择保存文件夹!")
        return
    #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
            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_path作为下载路径
            "download.default_directory": download_path, 
            "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()
                # 使用download_path拼接重命名路径
                original_file = os.path.join(download_path, "Documento de Arrecadação Municipal de Taxa de IPTU.pdf")
                new_file = os.path.join(download_path, f"{nome}.pdf")
                os.rename(original_file, new_file)
            except Exception as e:
                print(f"Erro: {str(e)} | 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
    global caminho
    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)


# 传递caminho作为参数给geraarquivos
botao_executa = ttk.Button(root, text="Executar",command= lambda: geraarquivos(caminho))
botao_executa.place(x=10,y=100)

root.mainloop()

关键修改点说明

  • 在Selecione_Arquivo()中添加global caminho,确保选择的路径被保存到全局变量
  • geraarquivos()新增download_path参数,函数内使用该参数替换硬编码的路径
  • 用os.path.join()拼接文件路径,避免手动拼接字符串出现的路径分隔符问题
  • 添加路径非空判断,防止用户未选择文件夹就点击执行按钮导致报错

内容的提问来源于stack exchange,提问作者Fernandolk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 05:35:01