【问题标题】:item pipeline executes for only last url in start_requests项目管道仅针对 start_requests 中的最后一个 url 执行
【发布时间】:2018-01-07 18:31:34
【问题描述】:

我有一些带有“链接”属性的 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",
  .
  .
  .
}

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

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 分配的任何字段在输出文件中都不存在。 这是我在这段代码中的两个问题。

【问题讨论】:

  • 请显示完整的代码并更正其格式。

标签: python json scrapy


【解决方案1】:
with open('lastsecond/results/' + item['id'][0], 'w') as result:
    json.dump(dict(item), result)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-14
    • 2020-12-04
    • 1970-01-01
    • 2019-01-05
    • 2014-03-22
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    相关资源
    最近更新 更多