簡體   English   中英

如何獲得“for”循環的前 3 個結果?

[英]How can I get the first 3 results of a 'for' loop?

這是工作代碼:

import scrapy

class imdb_project(scrapy.Spider):
    name = 'imdb'
    start_urls = ['https://www.imdb.com/chart/top']

    def parse(self, response):
        for i in response.css('.titleColumn a'):
            movie_name = i.css('::text').get()
            movie_url = i.css('::attr(href)').get()
            dict = {'movie': movie_name}

            yield response.follow(movie_url, callback=self.parse_info, meta=dict)

    def parse_info(self, response):
        movie_name2 = response.meta['movie']
        duration = response.css('ul.dxizHm li:nth-child(3)::text').get()
        genre = ', '.join(response.css('a.ipc-chip--on-baseAlt *::text').getall())

        print('\n')
        yield {
            'Movie Name': movie_name2,
            'Duration': duration,
            'Genre': genre,
        }
        print('\n')

這向我顯示了所有 250 個結果,但如果我只想查看前 3 個結果怎么辦?

更改列表迭代

for i in response.css('.titleColumn a'):    

到:

for i in response.css('.titleColumn a')[:3]:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM