python中的webscraping和GUI。应用程序冻结

2024-04-26 05:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我在运行我的应用程序时遇到了问题。我是新的编码,所以任何建议我的代码将不胜感激。我正在尝试为我的webscrapper制作一个GUI。没有图形用户界面,它可以很好地工作,并将所有信息刮到一个.csv文件中。然后,当我用按钮创建GUI使其运行时,它冻结了。我试着把睡眠调到根.aftero甚至删除那一行,因为我在其他线程中读到这是GUI冻结的主要原因,但仍然无法修复它。你知道吗

另外,在我定义的函数中,我不确定是否可以随意使用“prices”这样的词,因为我没有使用它,或者什么是正确的方法。你知道吗

这是我的密码,提前谢谢。你知道吗

import requests
from bs4 import BeautifulSoup
from time import sleep
from random import randint
import csv
import os
from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Mercados App")
root.geometry("500x500")
app = Frame(root)


def updating(prices):

switch = True
if switch:
    f = open("ListaDePreciosTodos.csv", "wt", newline="")
    writer = csv.writer(f)

    file_lista_productosPV = open("ListaPV", "r")
    lista_productosPV = file_lista_productosPV.readlines()

    file_lista_productosT = open("ListaT", "r")
    lista_productosT = file_lista_productosT.readlines()

    file_lista_productosW = open("ListaW", "r")
    lista_productosW = file_lista_productosW.readlines()
    writer.writerow(["PV Producto", "PV Precio", "T Producto", "T Precio",
                     "W Producto", "W Precio"])

    os.system('say "Price updates starting now"')

    for searchPV, searchT, searchW in zip(lista_productosPV, lista_productosT, lista_productosW):
        urlPV = "https://www.pv.com/" + searchPV.strip() + "/p"
        rPV = requests.get(urlPV)
        soupPV = BeautifulSoup(rPV.content, "lxml")
        urlT = "http://www.T.com.pe/t/product/" + searchT.strip() + "?navAction=jump&navCount=2"
        rT = requests.get(urlT)
        soupT = BeautifulSoup(rT.content, "lxml")
        urlW = "https://www.w.com/" + searchW.strip() + "/p"
        rW = requests.get(urlW)
        soupW = BeautifulSoup(rW.content, "lxml")

        try:
            productoPV = soupPV.find(["div"], {"class": ["g-nombre-prod"]}).text
            precioPV = soupPV.find(["strong"], {"class": ["skuBestPrice"]}).text

            productoT = soupT.find(["div"], {"class": ["title"]}).h5.text
            precioTxKG = soupT.find(["div"], {"class": ["price-unit"]}).text
            precioTxUN = soupT.find(["span"], {"class": ["active-price"]}).span.text

            if precioTxKG.strip() is "":
                precio_final_t = precioTxUN.replace("S/ ", "").strip()

            else:
                precio_final_t = precioTxKG.replace("/KG)","").replace("(","").replace("S/ ","").strip()

            productoW = soupW.find(["div"], {"class": ["name"]}).text
            precioW = soupW.find(["strong"], {"class": ["skuBestPrice"]}).text


            writer.writerow([productoPV, precioPV.replace("S/", ""),
                             productoT.replace("VERDURAS" or "FRUTAS" or "T", "").strip(),
                             precio_final_t, productoW, precioW.replace("S/. ", "")])

        except AttributeError:

            try:
                writer.writerow([productoPV, "No Disp.",
                                productoT.replace("VERDURAS" or "FRUTAS" or "T", "").strip(),
                                precio_final_t, productoW, precioW.replace("S/. ", ""), ])

            except AttributeError:

                try:
                    writer.writerow([productoPV, precioPV.replace("S/", ""),
                                    productoT.replace("VERDURAS" or "FRUTAS" or "T", "").strip(),
                                    "No Disp.", productoW, precioW.replace("S/. ", ""), ])

                except:
                    writer.writerow([productoPV, precioPV.replace("S/", ""),
                                     productoT.replace("VERDURAS" or "FRUTAS" or "T", "").strip(),
                                     precio_final_t, productoW, "No Disp."])

    f.close()
    os.system('say "your file is ready"')


def stopupdating(prices):
    global switch
    switch = False


app.grid()

Label(root, text="Bienvenidos").grid(row=0, column=1, sticky=W, padx=8)

startButton = Button(root, text="Start updating prices")
startButton.bind("<Button-1>", updating)
startButton.grid(row=1, column=1, sticky=W, padx=10)

stopButton = Button(root, text="Stop updating prices")
stopButton.bind("<Button-1>", stopupdating)
stopButton.grid(row=2, column=1, sticky=W, padx=10)

root.mainloop()

Tags: ortextfromimportrootfindreplaceclass
1条回答
网友
1楼 · 发布于 2024-04-26 05:14:50

在代码中,创建一个新方法:

def start_update():
    threading.Thread(target=updating).start()

您还需要添加import threading。你知道吗

并将按钮绑定到此方法,而不是直接绑定到updating。我看到你的updating方法有一个参数prices,但我看不到它在你的代码中是如何分配的,甚至在哪里被使用。你知道吗

相关问题 更多 >

    热门问题