Невозможно получить ссылку на следующую страницу с JavaScript в Scrapy и Python - PullRequest
0 голосов
/ 09 октября 2018

У меня проблема с получением ссылки на следующую страницу с python.

Код

import scrapy
from scrapy.http import Request
from gharbheti.items import GharbhetiItem
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, Identity, MapCompose, Join, Compose
from urllib.parse import urljoin

    class ListSpider(scrapy.Spider):
    name = 'list'
    allowed_domains = ['gharbheti.com']
    start_urls = ['https://www.gharbheti.com/sale','https://www.gharbheti.com/rent']

        def parse(self, response):
            properties=response.xpath('//li[@class="col-md-6 Search_building"]/descendant::a')
            for property in properties:
                link=property.xpath('./@href').extract_first()
                urls=response.urljoin(link)

                yield Request(urls,callback=self.parse_property, meta={'URL':urls, })

        def parse_property(self, response):
                l = ItemLoader(item=GharbhetiItem(), response=response)
                URL=response.meta.get('URL')
                l.add_value('URL', response.url)
                l.add_xpath('Title','//div[@class="product-page-meta"]/h4/em/text()',MapCompose(str.strip,str.title))
                l.add_xpath('Offering','//figcaption[contains(text(), "For Sale")]/text()|//figcaption[contains(text(),"For Rent")]/text()',MapCompose(lambda i:i.replace('For',''),str.strip))
                l.add_xpath('Price','//div[@class="deal-pricebox"]/descendant::h3/text()',MapCompose(str.strip))
                l.add_xpath('Type','//ul[@class="suitable-for"]/li/text()',MapCompose(str.strip))
                bike_parking=response.xpath('//i[@class="fa fa-motorcycle"]/following-sibling::em/text()').extract_first()
                car_parking=response.xpath('//i[@class="fa fa-car"]/following-sibling::em/text()').extract_first()
                parking=("Bike Parking: {} Car Parking: {}".format(bike_parking,car_parking))
                l.add_value('Parking',parking)
                l.add_xpath('Description','//div[@class="comment more"]/text()',MapCompose(str.strip))
                l.add_xpath('Bedroom','//i[@class="fa fa-bed"]/following-sibling::text()',MapCompose(lambda i:i.replace('Total Bed Room:',''),str.strip,int))
                l.add_xpath('Livingroom','//i[@class="fa fa-inbox"]/following-sibling::text()',MapCompose(lambda i:i.replace('Total Living Room:',''),str.strip,int))
                l.add_xpath('Kitchen','//i[@class="fa fa-cutlery"]/following-sibling::text()',MapCompose(lambda i:i.replace('Total kitchen Room:',''),str.strip,int))
                l.add_xpath('Bathroom','//i[@class="fa fa-puzzle-piece"]/following-sibling::text()',MapCompose(lambda i:i.replace('Total Toilet/Bathroom:',''),str.strip,int))
                l.add_xpath('Address','//b[contains(text(), "Map")]/text()',MapCompose(lambda i:i.replace('Map Loaction :-',''),str.strip))
                l.add_xpath('Features','//div[@class="list main-list"]/ul/li/text()',MapCompose(str.strip))

                images=response.xpath('//div[@class="carousel-inner dtl-carousel-inner text-center"]/descendant::img').extract()
                images=[s.replace('<img src="', '') for s in images]
                images=[i.split('?')[0] for i in images]
                Image=["http://www.gharbheti.com" + im for im in images]
                l.add_value('Images',Image)

                return l.load_item()

Не удается получить следующую страницу из сети. Для другого сайта этоэто то, что я сделал (простая нумерация страниц без JavaScript

next_page=response.urljoin(response.xpath('//a[contains(text(), "Next")]/@href').extract_first()

yield Request(next_page, callback=self.parse)

1 Ответ

0 голосов
/ 09 октября 2018

Поскольку для нумерации страниц используется javascript, в исходном коде страницы нет ссылки.

Чтобы увидеть, что происходит:

  1. Откройте инспектор браузера (F12 в Chrome) и перейдитена вкладку сети
  2. Нажмите кнопку «Загрузить еще» на пользовательском интерфейсе веб-страницы

Инспектор покажет вам, что сайт отправляет запрос асинхронной формы POST на https://www.gharbheti.com/RoomRentHome/GetPropertiesForRent,с двумя значениями для данных формы:

  1. RentTypeId: 0 {не уверен, что это такое, но я уверен, что вы можете понять это, если вам нужно знать}
  2. page: 1 {увеличивается с каждым нажатием кнопки «Загрузить еще»}

Вам придется использовать программный подход, используя запрос формы .Похоже, что каждая страница дает еще 10 свойств, поэтому, если вы хотите получить следующие 1000 после начальной загрузки страницы, вы можете написать

for i in range(1,101):
    <send a form request with i as the page value>

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

...