首页 > 解决方案 > Scrapy - Xpath 在 shell 中工作,但在代码中不工作

问题描述

我正在尝试爬取一个网站(我得到了他们的授权),我的代码在scrapy shell中返回了我想要的东西,但我的蜘蛛没有得到任何东西。

我还检查了与此类似的所有先前问题,但没有任何成功,例如,该网站在主页中没有使用 javascript 来加载我需要的元素。

import scrapy


class MySpider(scrapy.Spider):
    name = 'MySpider'

    start_urls = [ #WRONG URL, SHOULD BE https://shop.app4health.it/ PROBLEM SOLVED!
        'https://www.app4health.it/',
    ]

    def parse(self, response):
        self.logger.info('A response from %s just arrived!', response.url)
        print ('PRE RISULTATI')

        results =  response.selector.xpath('//*[@id="nav"]/ol/li[*]/a/@href').extract()
        # results = response.css('li a>href').extract()


        # This works on scrapy shell, not in code
        #risultati =  response.xpath('//*[@id="nav"]/ol/li[1]/a').extract()
        print (risultati)




        #for pagineitems in risultati:
               # next_page = pagineitems 
        print ('NEXT PAGE')
        #Ignores the request cause already done. Insert dont filter
        yield scrapy.Request(url=risultati, callback=self.prodotti,dont_filter = True)

    def prodotti(self, response):
        self.logger.info('A REEEESPONSEEEEEE from %s just arrived!', response.url)
        return 1

我要抓取的网站是https://shop.app4health.it/

我使用的 xpath 命令是这个:

response.selector.xpath('//*[@id="nav"]/ol/li[*]/a/@href').extract()

我知道prodotti函数 ecc存在一些问题...,但这不是重点。我想了解为什么 xpath 选择器与 scrapy shell 一起工作(我得到了我需要的链接),但是当我在我的蜘蛛中运行它时,我总是得到一个空列表。

如果它有帮助,当我在我的蜘蛛中使用 CSS 选择器时,它可以正常工作并且可以找到元素,但我想使用 xpath(我在未来的应用程序开发中需要它)。

谢谢您的帮助 :)

编辑:我试图打印第一个响应的正文(来自 start_urls),这是正确的,我得到了我想要的页面。当我在我的代码中使用选择器(甚至是建议的选择器)时,它们在 shell 中都可以正常工作,但我的代码中什么也没有!

编辑 2 我对 Scrapy 和网络爬虫有了更多的经验,我意识到有时,您在浏览器中获得的 HTML 页面可能与您通过 Scrapy 请求获得的页面不同!以我的经验,与您在浏览器中看到的相比,某些网站会以不同的 HTML 响应!这就是为什么有时如果您使用从浏览器获取的“正确”xpath/css 查询,如果在您的 Scrapy 代码中使用它可能不会返回任何内容。始终检查您的回复内容是否符合您的预期!

已解决:路径正确。我写错了 start_urls!

标签: pythonxpathweb-scrapingweb-crawlerscrapy-spider

解决方案


    //nav[@id="mmenu"]//ul/li[contains(@class,"level0")]/a[contains(@class,"level-top")]/@href 

使用这个xpath,在创建xpath之前还要考虑页面的'view-source'


推荐阅读