我大约有十二个python模块导入,可以在许多不同的scraper上重用,我很想将它们放入一个文件(scraper_functions.py)中,该文件还包含许多函数,如下所示:
import smtplib
import requests
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
import time
def function_name(var1)
# function code here
然后在我的刮板上,我只想做类似的事情:
import scraper_functions
并完成它。但是,将导入内容列在scraper_functions.py的顶部是行不通的,也不能将所有导入内容都放入一个函数中。在每种情况下,我在进行导入的刮板中都会遇到错误。
Traceback (most recent call last):
File "{actual-scraper-name-here}.py", line 24, in <module>
x = requests.get(main_url)
NameError: name 'requests' is not defined
此外,在VSCode中,在“问题”下,出现类似错误
Undefined variable 'requests' pylint(undefined-variable) [24,5]
没有一个模块被识别。我确保所有文件都在同一目录中。
请问有可能吗?
答案 0 :(得分:1)
您需要使用scraper_functions
前缀(使用此导入名称的相同方式)或使用from
关键字通过scraper_functions
从*
导入内容选择器。
使用form
关键字(推荐)
from scraper_functions import * # import everything with *
...
x = requests.get(main_url)
使用scraper_functions
前缀(不推荐)
import scraper_functions
...
x = scraper_functions.requests.get(main_url)