我已导入一个函数,但无法使用其中的变量

2024-09-30 22:15:32 发布

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

因此,我将其作为导入文件:

from bs4 import BeautifulSoup as bs
import requests
import time

def soupIt(URL, osztaly, pls):
    global full
    global noedit
    global ft
    global ftfull
    global eur
    global eurfull
    global dollar
    global dollarfull
    content = requests.get(URL)
    soup = bs(content.text, 'html.parser')
    do = soup.find_all(pls, class_ = osztaly)[0].get_text()
    noedit = do.strip()
    do = noedit.replace('.', '')
    do = do.replace(',', '')
    do = do.replace(' ', '')
    do = do.replace('  ', '')
    do = do.replace('Ft', '')
    do = do.replace('$', '')
    full = do.replace('€', '')
    ft = noedit + " Ft"
    ftfull = full + " Ft"
    eur = noedit + " €"
    eurfull = full + " €"
    dollar = noedit + " $"
    dollarfull = full + " $"
    

我尝试在我尝试的文件中使用它soupIt()

from scrhelp import soupIt
soupIt("https://www.emag.hu/aoc-gaming-monitor-ips-23-8-full-hd-1-ms-144hz-freesync-dp-hdmi-fekete-24g2u-bk/pd/D0HVSGBBM/",'product-new-price', "")
print(full)
 

这给了我一个错误:

Traceback (most recent call last): File "D:\Donát\Programozás\Phyton\webscraper\apitest.py", line 3, in print(full) NameError: name 'full' is not defined

我试图在我试图使用它的文件中将它设置为globalfullglobal,但它不起作用,而且我是python新手


Tags: 文件fromimporturlbsrequestsglobaldo
2条回答

您只将函数soupIt导入了命名空间。变量full仅对模块是全局变量。您还需要从scrhelp导入full

我试着做一个简单的例子:

class CoolClass():
    
    def __init__(self):
        self.cool_variable = "test"
        

TestClass = CoolClass()
print(TestClass.cool_variable)
#out: test

TestClass.cool_variable = "new value"
print(TestClass.cool_variable)
#out: new value

init方法在从类创建对象时执行。 这意味着您可以像下面这样设置一个变量,并通过编写:ObjectName.variablename来获取值,如示例所示。当然,您也可以在类内修改它,或者在类外的示例中修改它

因此,这也适用于您导入的类

相关问题 更多 >