【问题标题】:Scrapy Last Page is not null and after page 146 last page is showing againScrapy Last Page 不为空,并且在第 146 页后,最后一页再次显示
【发布时间】:2020-11-11 09:57:03
【问题描述】:

该网站有 146 个页面,但在第 146 页之后,最后一页再次显示。 `

     if next_page is not None:

         yield response.follow(next_page, callback = self.parse)`

使用这种方法,spider 不会在第 146 页停止,它会继续,因为第 147,148,149..与第 146 页相同。我尝试使用 for 循环,但没有奏效。另外,我尝试在下一页按钮中获取值并使用 next_extract 中断该功能。顺便说一下,next_extract 的输出是 ['kelimeler.php?s=1'] 并且数字随着页码的增加而增加,例如 ['kelimeler.php?s=2']。而且,这种方式也行不通。

         next_page = response.css('div.col-md-6.col-sm-6.col-xs-6:nth-child(2) a::attr(href)').get()
     next_extract = response.css('div.col-md-6.col-sm-6.col-xs-6:nth-child(2) a').xpath("@href").extract()

     print(next_page)
     print(next_extract)




     
     if next_extract is 'kelimeler.php?s=147':
         break
     if next_page is not None:
         yield response.follow(next_page, callback = self.parse)

我应该怎么做才能停止第 146 页的抓取?

这就是整个解析函数

     def parse(self,response):

     items = TidtutorialItem()

     all_div_kelimeler = response.css('a.collapsed')

     for tid in all_div_kelimeler:

         kelime = tid.css('a.collapsed::text').extract()
         link= tid.css('a.collapsed::text').xpath("@href").extract()


         items['Kelime'] = kelime
         items['Link'] = link

         yield items

     next_page = response.css('div.col-md-6.col-sm-6.col-xs-6:nth-child(2) a::attr(href)').get()
     next_extract = response.css('div.col-md-6.col-sm-6.col-xs-6:nth-child(2) a').xpath("@href").extract()

     print(next_page)
     print(next_extract)


     if next_page is not None:
     #if next_extract is not 'kelimeler.php?s=2':
     #for i in range (10):
         yield response.follow(next_page, callback = self.parse)

【问题讨论】:

    标签: python html css scrapy css-selectors


    【解决方案1】:

    如果没有看到该页面,我无法非常准确地确定最佳方法,但我可以给你一些建议。

         next_page = response.css('div.col-md-6.col-sm-6.col-xs-6:nth-child(2) a::attr(href)').get()
         next_extract = response.css('div.col-md-6.col-sm-6.col-xs-6:nth-child(2) a').xpath("@href").extract()
    

    我不确定您在这里要完成什么,因为这两个选择器本质上是相同的,除了第二个您使用的是 .extract() 方法,它返回一个 LIST .由于它返回一个列表,因此以下行将总是失败:

        if next_extract is 'kelimeler.php?s=147':
            break
    

    另一个重要的一点是break 是在循环中使用的,所以如果if 语句 曾经解析为True,这将导致异常。阅读更多here

    再一次,没有看到页面我不能肯定地说,但我相信这会完成你想要做的事情:

        if next_page == 'kelimeler.php?s=147':
             return
    

    注意 next_page 而不是 next_extract。如果你想使用后者,记住它是一个列表,而不是一个字符串。

    【讨论】:

    • 答案有效。另外,感谢您提供有关 break 的解释和信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多