Проблема с такими же данными при сканировании веб-страницы - PullRequest
0 голосов
/ 26 марта 2019

Я пытаюсь сканировать веб-страницу, чтобы получить отзывы и рейтинги этой веб-страницы.Но я получаю те же данные, что и выходные данные.

import scrapy
import json
from scrapy.spiders import Spider


class RatingSpider(Spider):
    name = "rate"

    def start_requests(self):
        for i in range(1, 10):
            url = "https://www.fandango.com/aquaman-208499/movie-reviews?pn=" + str(i)
            print(url)
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        print(json.dumps({'rating': response.xpath("//div[@class='star-rating__score']").xpath("@style").extract(),
               'review': response.xpath("//p[@class='fan-reviews__item-content']/text()").getall()}))

ожидается: сканирование 1000 страниц веб-сайта https://www.fandango.com/aquaman-208499/movie-reviews

фактический вывод:

https://mobile.fandango.com/aquaman-208498/movie-reviews?pn=1
{"rating": ["width: 90%;", "width: 100%;", "width: 100%;", "width: 100%;", "width: 100%;", "width: 60%;"], "review": ["Everything and more that you would expect from Aquaman. Lots of action, humor, interpersonal conflict, and some romance.", "Best Movie ever action great story omg DC has stepped its game up excited for the next movie \n\nTotal must see total", "It was Awesome! Visually Stunning!", "It was fantastic five stars", "Very chaotic with too much action and confusion."]}

https://mobile.fandango.com/aquaman-208499/movie-reviews?pn=9
{"rating": ["width: 90%;", "width: 100%;", "width: 100%;", "width: 100%;", "width: 100%;", "width: 60%;"], "review": ["Everything and more that you would expect from Aquaman. Lots of action, humor, interpersonal conflict, and some romance.", "Best Movie ever action great story omg DC has stepped its game up excited for the next movie \n\nTotal must see total", "It was Awesome! Visually Stunning!", "It was fantastic five stars", "Very chaotic with too much action and confusion."]}

1 Ответ

0 голосов
/ 27 марта 2019

Обзоры динамически заполняются с помощью JavaScript.Вы должны проверять запросы, сделанные сайтом, в тех случаях, когда это нравится.

URL-адрес для получения отзывов пользователей:

https://www.fandango.com/napi/fanReviews/208499/1/5

Возвращает json с 5 отзывами.

Ваш паук может быть переписан так:

import scrapy
import json
from scrapy.spiders import Spider


class RatingSpider(Spider):
    name = "rate"

    def start_requests(self):
        movie_id = "208499"
        for page in range(1, 10):
            # You have to pass the referer, otherwise the site returns a 403 error
            headers = {'referer': 'https://www.fandango.com/aquaman-208499/movie-reviews?pn={page}'.format(page=page)}
            url = "https://www.fandango.com/napi/fanReviews/208499/{page}/5".format(page=page)
            yield scrapy.Request(url=url, callback=self.parse, headers=headers)

    def parse(self, response):
        data = json.loads(response.text)
        for review in data['data']:
            yield review

Обратите внимание, что я также использую yield вместо print для извлечения элементов, вот какScrapy ожидают, что предметы будут созданы.Вы можете запустить этот паук следующим образом, чтобы экспортировать извлеченные элементы в файл:

scrapy crawl rate -o outputfile.json

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...