Соскоб с нумерацией страниц с использованием Scrapy и Python - PullRequest
0 голосов
/ 25 апреля 2019

Я пытаюсь очистить все записи сайта и доступный контент, чтобы попытаться изучить их с помощью скрапа.До сих пор я был в состоянии очистить все записи блога на странице, а затем перейти на следующую страницу и очистить содержимое там.Я также нашел ссылку на следующую страницу.Тем не менее, я не могу понять, как действовать дальше, хотя я прочитал немало учебников и посмотрел пример кода.У меня пока что:

class SaltandLavender(CrawlSpider):
    logging.getLogger('scrapy').propagate = False
    name = 'saltandlavender'
    allowed_domains=['saltandlavender.com']
    start_urls=['https://www.saltandlavender.com/category/recipes/']
    rules = (
        Rule(LinkExtractor(allow='https://www.saltandlavender.com/category/recipes/'),  callback="parse", follow= True),
    )


    def parse(self,response):
        #with open('page.html', 'wb') as html_file:
        #   html_file.write(response.body)
        print "start 1"
        for href in response.css('.entry-title a'):
            print "middle 1"
            yield response.follow(href, callback=self.process_page)
        next=response.css('li.pagination-next a::text')
        if next:
            url=''.join(response.css('li.pagination-next a::attr(href)').extract())
            print url
            Request(url)



    def process_page(self,response):
        print "start 2"
        post_images=response.css('div.entry-content img::attr(src)').extract()
        content =  {
                    'cuisine':''.join(response.xpath(".//span[@class='wprm-recipe-cuisine']/descendant::text()").extract()),
                    'title': ''.join(response.css('article.format-standard h1.entry-title::text').extract()),
                    #'content': response.xpath(".//div[@class='entry-content']/descendant::text()").extract(),
                    'ingredients': ''.join(response.css('div.wprm-recipe-ingredients-container div.wprm-recipe-ingredient-group').extract()),
                    #'time':response.css('wprm-recipe-total-time-container'),
                    'servings':''.join(response.css('span.wprm-recipe-servings::text').extract()),
                    'course':''.join(response.css('span.wprm-recipe-course::text').extract()),
                    'preparation':''.join(response.css('span.wprm-recipe-servings-name::text').extract()),
                    'url':''.join(response.url),
                    'postimage':''.join(post_images[1])
                    }
        #print content
        print "end 2"

    def errorCatch(self):
        print "Script encountered an error. Check selectors for changes in the site's layout and design..."
        return

    def updateValid(self):
        return



if __name__ == "__main__":
    LOG_ENABLED = False
    process = CrawlerProcess({
        #random.choice(useragent)
        'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
    })
    process.crawl(SaltandLavender)
    process.start()

Ответы [ 2 ]

1 голос
/ 25 апреля 2019

Что-то не так с вашей следующей страницей запроса. Например, вы используете переменную next, которая является встроенным зарезервированным словом, а также вы не выдаете следующий запрос. Проверьте это исправление:

def parse(self,response):
    for href in response.css('.entry-title a'):
        yield response.follow(href, callback=self.process_page)
    next_page = response.css('li.pagination-next a::attr(href)').get()
    if next_page:
        yield response.follow(next_page)
0 голосов
/ 25 апреля 2019

Вам нужно выдать запрос, а не просто создать его экземпляр.

Заменить:

Request(url)

на:

yield Request(url)
...