从另一个Python脚本导入函数时,如何确保导入的模块正常工作?

2024-04-19 22:47:21 发布

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

为了简化当前的脚本,我决定将一些函数移到一个单独的脚本中。其中之一如下:

def get_soup(url):
    """
    Given the url of a page, this function returns the soup object.

    Parameters:
        url: the link to get soup object for

    Returns:
        soup: soup object
    """

    driver = webdriver.Firefox()
    driver.get(url)
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')
    driver.close()

    return soup

这个函数放在一个名为scrape_data.py的文件中。然而,当我在当前脚本中导入这个函数后使用它时,我得到了NameError: name 'BeautifulSoup' is not defined。即使在我将BeautifulSoup导入当前脚本之后,也会发生这种情况,如下所示:

from bs4 import BeautifulSoup
from selenium import webdriver

那我该怎么做呢?我是否应该将函数所需的模块/库导入函数本身(这对我也不起作用)?谢谢!你知道吗

enter image description hereenter image description here


Tags: the函数fromimport脚本urlgetobject