LinkExtractor不起作用-需要运行自定义代码

时间:2019-03-26 14:59:26

标签: scrapy

我正在尝试抓取网站。它具有分页的索引页和详细页。爬网程序在详细信息页面上可以正常工作,但是水平爬网在索引页面上无法正常工作。这是由于水平页面上的“下一步”项没有供爬网程序使用的网址所致。我已经使用Selinium解决了这个问题,但是我不知道如何将其添加到爬虫中。

我尝试覆盖parse函数,但这会破坏搜寻器。

from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.loader.processors import MapCompose,Join
from scrapy.loader import ItemLoader
from ..items import PropertiesItem
import datetime
import socket


class EasySpider(CrawlSpider):
    name = 'easy'
    allowed_domains = ['www.example.co.uk']
    start_urls = ['https://www.example.co.uk/starturl']

    rules = (
        Rule(LinkExtractor(restrict_xpaths='//*[contains(@class,"pagination-direction-next")]'), callback='parse_horizontal'),
        Rule(LinkExtractor(restrict_xpaths='//*[contains(@class, "propertyCard-img-link aspect-3x2 ")]'), callback='parse_item')
    )

    def parse_horizontal(self, response):
        l = ItemLoader(item=PropertiesItem(), response=response)
        l.add_value('url', response.url)
        return l.load_item()
        #add additional code here that yields the URLS


    def parse_item(self, response):
        #item = {}
        #item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get()
        #item['name'] = response.xpath('//div[@id="name"]').get()
        #item['description'] = response.xpath('//div[@id="description"]').get()
        #return item
        l = ItemLoader(item=PropertiesItem(), response=response)

        l.add_xpath('price', '//*[@id="propertyHeaderPrice"]/strong/text()',
                    MapCompose(lambda i: i.replace(',', ''), float), re='[,.0-9]+')

        # Housekeeping fields
        l.add_value('url', response.url)
        l.add_value('project', self.settings.get('BOT_NAME'))
        l.add_value('spider', self.name)
        l.add_value('server', socket.gethostname())
        l.add_value('date', datetime.datetime.now())

        return l.load_item()

我希望parse_horizo​​ntal在遇到“ pagination-direction-next”类时运行。但是,该类包含您可以在网站上单击的按钮,但不包含实际的URL。我猜这就是为什么永远不会触发回调,却不知道该怎么做的原因。

因此,当前,当我运行代码时,它会从起始页面上具有链接的详细信息页面中抓取信息,但不会从起始页面水平导航到下一个索引页面。

0 个答案:

没有答案