这里是Python初学者。假设我有三种抓取网站的方法。让我们叫他们scrape_site_a,scrape_site_b和scrape_site_c。我想运行其中的每一个,但是我想用这样的方式来定义它们,这样我就可以动态地调用它们,而不需要调用每个名称。理想情况下,我只想加载目录中的所有模块,并对每个模块调用相同的方法。到目前为止,我的尝试如下:
site_a.py
def scrape():
# scrape the sitesite_b.py
def scrape():
# scrape the sitesite_c.py
def scrape():
# scrape the site我已经设置了__init__.py,因此我可以执行以下操作:
scrape.py
from sites import *
site_a.scrape()
site_b.scrape()
site_c.scrape()我想做这样的事情:
for site in sites:
site.scrape()我意识到有一个基本的编程概念,我在这里不理解,我有两个问题:
发布于 2019-04-17 03:05:24
以下内容扫描给定的目录,加载其中的每个.py文件,如果存在模块的scrape方法,则调用它。
from os import listdir
from os.path import join
scraper_dir = "./scrapers"
for scraper_name in listdir(scraper_dir):
if scraper_name.endswith(".py"):
with open(join(scraper_dir, scraper_name)) as scraper_file:
scraper_globals = {} # this will hold scraper's globals
scraper_module = exec(scraper_file.read(), scraper_globals)
if "scrape" in scraper_globals: # we have a scrape method
scrape_method = scraper_globals["scrape"]
callable(scrape_method) and scrape_method() # call it发布于 2019-04-17 02:49:29
from sites import site_a,site_b,site_c
sites = [site_a,site_b,site_c]
for site in sites:
site.scrape()我想这可能就是你想要的
from sites import *
for item in globals():
if item.startswith("site_") and hasattr(globals()[item],'scrape'):
globals()[item].scrape()像这样的反省有点冒险.读者提防
发布于 2019-04-17 03:21:09
您会想要使用检查模块来处理类似的事情。
import inspect
modules = [mod for mod in globals() if inspect.ismodule(eval(mod))]将为您提供名称空间中的所有模块。如果您想要的话,您应该能够看到如何将其修改得更具体。诀窍是运行eval,将名称的字符串转换为对某个对象的引用,该对象可能是一个模块。
https://stackoverflow.com/questions/55719152
复制相似问题