项目管道仅对start_requests中的最后一个 URL 执行



我有一些带有"links"属性的JSON文件。以下是这些文件的示例:

{
"links": [
  "https://lastsecond.ir/hotels/1343-metropol-ankara",
  "https://lastsecond.ir/hotels/1347-bianco-boutique"
],
"names": [
  "Metropol Ankara hotel",
  "Bianco Boutique hotel",
  "Asal Ankara hotel",
  .
  .
  .
}

我需要阅读所有这些文件,对于每个链接,抓取页面并运行管道。某些文件仅在链接上,Item 管道为该文件正确运行,但对于具有多个链接的文件,Item 管道仅针对 JSON 文件的"links"属性中的最后一个链接运行。这是我到目前为止的蜘蛛代码:

class HotelInfoSpider(scrapy.Spider):
    def start_requests(self):
        files = [f for f in listdir('lastsecond/hotels/') if isfile(join('lastsecond/hotels/', f))]

    for file in files:
        with open('lastsecond/hotels/' + file, 'r') as hotel_info:
            hotel = json.load(hotel_info)
            for link in hotel["links"]:
                yield scrapy.Request(link, meta={'id': file})
    name = 'hotel_info'
    allowed_domains = ['lastsecond.ir']
    custom_settings = {
        'ITEM_PIPELINES': {
            'lastsecond.pipelines.hotelFile': 400
        }
    }
    def parse(self, response):
        tour = ItemLoader(item=tourItem(), response=response)
        tour.add_css('name', '.tours-list h5 a::text')
        tour.add_css('nights', '.tours-list ul.mx-1 li:last-child label::text')
        tour.add_value('found_date', str(datetime.now()))
        tour.add_value('id', response.meta['id'])
        yield tour.load_item()

这是我的管道代码:

class hotelFile(object):
    def process_item(self, item, spider):
        with open('lastsecond/results/' + item['id'][0], 'w') as result:
            json.dump(dict(item), result)
        return item

我还有另一个问题,在输出文件中,我只看到我分配的项目字段 add_value.我分配的任何字段add_css都不存在在输出文件中。这是我在这个代码中的两个问题。

with open('lastsecond/results/' + item['id'][0], 'w') as result:
    json.dump(dict(item), result)

您每次都会重新打开文件进行写入,这会导致您覆盖其内容。
您应该打开文件进行追加,或者只打开一次。

至于你的第二个问题,你的代码看起来应该可以工作。
确保 css 选择器实际上与您尝试提取的内容匹配(特别是第二个看起来非常具体(。

最新更新