Scrapy爬网转到下一页并返回

toe95027  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(195)

正如标题中提到的,我的蜘蛛去了第2页,又回到第1页。所以顺序是1-2-1。我不知道该去哪里找。

def parse(self, response):
    for products in response.css("div.z7ntrt-0.cLlfW.s1a29zcm-11.ggOMjb"):
       yield {
            "name": products.css("a.link-detail::attr(title)").get(),
            "link": products.css("a.link-detail").attrib["href"],
            "source": products.css("div.tag::text").get()
       }

    next_page = response.css("a.s1pk8cwy-4.eSWEIV::attr(href)").get()
    if next_page is not None:
        next_page_link=response.urljoin(next_page)
        yield scrapy.Request(url=next_page_link, callback= self.parse)
j8ag8udp

j8ag8udp1#

这是因为您使用的类名在网页的分页部分同时用作前进箭头和后退箭头。

但是,当前页面元素的class属性似乎有一个唯一的值,并且在每个页面上都是一致的,因此使用Xpath我们可以隔离当前页面,然后使用following-sibling指令获取紧接在当前页面之后的页面。
我已经测试过了,可以确认它确实如预期的那样工作。

def parse(self, response):
    for products in response.css("div.z7ntrt-0.cLlfW.s1a29zcm-11.ggOMjb"):
       yield {
            "name": products.css("a.link-detail::attr(title)").get(),
            "link": products.css("a.link-detail").attrib["href"],
            "source": products.css("div.tag::text").get()
       }
    next_page = response.xpath(
        '//a[contains(@class,"ctiKSh")]/following-sibling::a/@href'
    ).get()
    if next_page is not None:
        next_page_link=response.urljoin(next_page)
        yield scrapy.Request(url=next_page_link, callback= self.parse)

相关问题