在启动脚本/Scrapy时修改文件的路径



我有几个从core.py脚本启动的蜘蛛,如下所示:

# ----- This part launch all given spiders ----- #
process = CrawlerProcess(get_project_settings())
process.crawl(CarrefourSpider)
process.crawl(ParapharmaSpider)
process.crawl(EbaySpider)
process.start() # the script will block here until the crawling is finished

然而,每个spider都引用了一个文件:如果没有给出绝对路径,它就无法工作,所以现在看起来是这样的:

class CarrefourSpider(scrapy.Spider):
name = "carrefour_bot"
def start_requests(self):
base_url="https://new.carrefour.fr/s?q="
test_file = open(r"C:UsersUserscrapybotscrapybotspidersfilesto_collect_carrefour.csv", "r")
reader = csv.reader(test_file)
for row in reader:
if row:
url = row[0]
absolute_url = base_url+url
print(absolute_url)
yield scrapy.Request(absolute_url, meta={'dont_redirect': True, "handle_httpstatus_list": [302, 301, 502]}, callback=self.parse)

问题是,我不会是唯一一个使用这个脚本的人。我想知道是否有一种方法可以在启动core.py脚本之前指定路径,而不是在每个脚本中修改路径。或者只是让它更灵活的想法:]

如果我不清楚,请告诉我!感谢您的帮助

from os import path
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, './output03.txt')
print(file_path)
fptr = open(file_path, 'w')

通过这种方式,将选择脚本所在的目录

一种更优雅的方法是利用杂乱的设置:

class CarrefourSpider(scrapy.Spider):
name = "carrefour_bot"
def start_requests(self):
base_url="https://new.carrefour.fr/s?q="
test_file = open(self.settings["URL_FILE_LOCATION"], "r")
reader = csv.reader(test_file)
for row in reader:
if row:
url = row[0]
absolute_url = base_url+url
print(absolute_url)
yield scrapy.Request(absolute_url, meta={'dont_redirect': True, "handle_httpstatus_list": [302, 301, 502]}, callback=self.parse)

现在,每个用户都可以在本地设置中自定义URL_FILE_LOCATION的值。

最新更新