代码之家  ›  专栏  ›  技术社区  ›  Morton

如果href为none,如何跳过?

  •  0
  • Morton  · 技术社区  · 6 年前

    我解析一个页面有20个href指向下一个页面。这样地: enter image description here

    但其中一个没有 href enter image description here

    它会导致我的代码失败。

        i = 1000
        j = 0
        dataLen = len(response.xpath('//div[@class="rank_list table rankstyle1"]//div[@class="tr"]'))
        photoNodes = response.xpath('//div[@class="rank_list table rankstyle1"]//div[@class="tr"]')
        for photoNode in photoNodes:
            contentHref = photoNode.xpath('.//a/@href').extract_first()
            yield Request(contentHref, callback=self.parse_page, priority = i, dont_filter=True)
            i -= 1
            j += 1  
        # start parse next page
        def parse_page(self, response):       
            global countLen, dataLen
            enName = response.xpath('//*[@class="movie_intro_info_r"]/h3/text()').extract_first()
            cnName = response.xpath('//*[@class="movie_intro_info_r"]/h1/text()'
            ...
    

    我想补充一下 if not (photoNode is None): if not photoNode =="" 还是不行。

    i = 1000
    j = 0
    dataLen = len(response.xpath('//div[@class="rank_list table rankstyle1"]//div[@class="tr"]'))
    photoNodes = response.xpath('//div[@class="rank_list table rankstyle1"]//div[@class="tr"]')
    for photoNode in photoNodes:
        if not (photoNode is None):
            contentHref = photoNode.xpath('.//a/@href').extract_first()
            # photoHref = photoNode.xpath('.//a/img/@src').extract_first()
            yield Request(contentHref, callback=self.parse_page, priority = i, dont_filter=True)
            i -= 1
            j += 1  
        else:
            pass
    twRanking['movie'] = movieArray
    

    我不知道如何跳过它,如果它可能没有一个

    任何帮助都将不胜感激。提前谢谢。

    1 回复  |  直到 6 年前
        1
  •  2
  •   kosist    6 年前

    看来,你需要检查一下 contentHref 不是空的,不是空的 photoNode . 反正会包含信息,所以不会是空的。尝试以下操作:

    for photoNode in photoNodes:
        contentHref = photoNode.xpath('.//a/@href').extract_first()
        if contentHref:
            # photoHref = photoNode.xpath('.//a/img/@src').extract_first()
            yield Request(contentHref, callback=self.parse_page, priority = i, dont_filter=True)
            i -= 1
            j += 1  
        else:
            pass