在python中的另一个脚本中导入项目文件

2024-03-29 15:53:25 发布

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

我正努力做到以下几点:

  1. 蜘蛛抓取网站网页上的链接。在
  2. 链接保存在文件中。在
  3. 另一个spider现在打开文本文件,读取链接,抓取各个web页面并保存数据。在

我试图从另一个python脚本调用这些spider which resides in a different directory。现在第一个spider被正确调用,没有任何问题。 问题出在第二个蜘蛛上。在

第二个spider的源代码如下:

import scrapy
from dateutil.parser import parse
import requests
from scrapy.http import Request
from project-name.items import Project-nameItem

url_list = []
with open("file.txt", "r") as f:
    for line in f:
        url_list.append(line)
for i in range(0, len(url_list)):
    url_list[i] = url_list[i].replace('\n','')
indexList = [] 
URL = "http://www.exaple.com/id=%s"
number = 0

class AnotherSpider(scrapy.Spider):
    name = "another"

    allowed_domains = ['example.com']

    start_urls = [URL % number]

    def start_requests(self):
        for i in url_list:
            yield Request(url = URL % i, callback = self.parse)

    def parse(self, response):
        #scrape the page for the required information

当我调用第二个蜘蛛时,我得到的错误是:

^{pr2}$

编辑

因为python脚本在不同的目录中,所以我使用runspider命令来执行spider。此命令的问题在于它是全局级命令,这意味着不考虑项目设置。这很可能导致python脚本无法识别items.py文件

用于执行蜘蛛的命令如下:

scrapy runspider spider1.py

scrapy runspider spider2.py

附近有工作吗?在


Tags: infromimport命令self脚本urlfor