【问题标题】:Scraping 'next' page after finishing in the main one using Rules使用规则完成主页面后抓取“下一页”
【发布时间】:2019-06-07 09:46:20
【问题描述】:

我正在尝试制作一个从页面中抓取产品的蜘蛛,完成后,抓取目录上的下一页以及之后的下一个页面,等等。

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

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。

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

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

【问题讨论】:

  • 相对的 URL 应该不是问题。由于这是 Amazon,我鼓励您编写一个常规蜘蛛(而不是 CrawlSpider 子类),以便能够更轻松地调试您的蜘蛛并能够处理您可能遇到的复杂场景。

标签: python-3.x web-scraping scrapy


【解决方案1】:

尝试使用 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 函数获取到单个页面的链接,从而产生对 parse 函数的响应,您还可以产生对同一函数的下一页响应,直到您已经浏览了所有页面。


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")

【讨论】:

  • 谢谢!但是我应该把连接的链接放在哪里,以便蜘蛛在页面完成后继续抓取?我现在使用的唯一函数是我拥有的 parse_item,它从产品中抓取数据
  • 感谢您的回答!我会试试这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
相关资源
最近更新 更多