使用规则在主页面完成后抓取'next'页面



我正在尝试制作一个蜘蛛,它可以从页面上抓取产品,完成后,抓取目录上的下一页和之后的下一页,依此类推。

从一个页面(我正在抓取亚马逊(中获得了所有产品

rules = {
        Rule(LinkExtractor(allow =(), restrict_xpaths = ('//a[contains(@class, "a-link-normal") and contains(@class,"a-text-normal")]') ), 
                                callback = 'parse_item', follow = False)
    }

这很好用。问题是我应该转到"下一个"页面并继续抓取。

我试图做的是这样的规则

rules = {
        #Next Button
        Rule(LinkExtractor(allow =(), restrict_xpaths = ('(//li[@class="a-normal"]/a/@href)[2]') )),
}

问题是 xPath 返回(例如,从此页面返回:https://www.amazon.com/s?k=mac+makeup&lo=grid&page=2&crid=2JQQNTWC87ZPV&qid=1559841911&sprefix=MAC+mak%2Caps%2C312&ref=sr_pg_2(

/s?k=mac+makeup&lo=grid&page=3&crid=2JQQNTWC87ZPV&qid=1559841947&sprefix=MAC+mak%2Caps%2C312&ref=sr_pg_3

这将是下一页的 URL,但没有 www.amazon.com。

我认为我的代码不起作用,因为我缺少上面 url 之前的 www.amazon.com。

知道如何使这项工作吗?也许我这样做的方式不正确。

尝试使用 urljoin。

link = "/s?k=mac+makeup&lo=grid&page=3&crid=2JQQNTWC87ZPV&qid=1559841947&sprefix=MAC+mak%2Caps%2C312&ref=sr_pg_3"

new_link = response.urljoin(link)

以下蜘蛛是一个可能的解决方案,主要思想是使用 parse_links 函数获取指向单个页面的链接,从而产生对解析函数的响应,您还可以生成对同一函数的下一页响应,直到您爬过所有页面。


class AmazonSpider(scrapy.spider):
    start_urls = ['https://www.amazon.com/s?k=mac+makeup&lo=grid&crid=2JQQNTWC87ZPV&qid=1559870748&sprefix=MAC+mak%2Caps%2C312&ref=sr_pg_1'
    wrapper_xpath = '//*[@id="search"]/div[1]/div[2]/div/span[3]/div[1]/div' # Product wrapper
    link_xpath = './//div/div/div/div[2]/div[2]/div/div[1]/h2/a/@href' # Link xpath
    np_xpath = '(//li[@class="a-normal"]/a/@href)[2]' # Next page xpath

    def parse_links(self, response):
        for li in response.xpath(self.wrapper_xpath):
            link = li.xpath(self.link_xpath).extract_first()
            link = response.urljoin(link)
            yield scrapy.Request(link, callback = self.parse)
        next_page = response.xpath(self.np_xpath).extract_first()
        if next_page is not None:
            next_page_link = response.urljoin(next_page)
            yield scrapy.Request(url=next_page_link, callback=self.parse_links)
        else:
            print("next_page is none")

最新更新