Scrapy Xpath在shell中工作,但在cod中不起作用

2024-10-01 09:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图爬网一个网站(我得到了他们的授权),我的代码返回了我想要的东西,但我的蜘蛛什么也没有。在

我还检查了前面所有类似于这个问题的问题,没有成功,例如,网站没有在主页中使用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命令是:

^{pr2}$

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

如果有帮助的话,当我在spider中使用CSS选择器时,它可以很好地工作并找到元素,但是我希望使用xpath(在我的应用程序的未来开发中需要它)。在

感谢您的帮助:)

编辑: 我试着打印第一个响应的主体(从起始网址),它是正确的,我得到了我想要的页面。当我在代码中使用选择器时(即使是建议的选择器),它们在shell中都可以正常工作,但我的代码中什么也得不到!在

编辑2 我对抓痒和网页抓取越来越有经验了,我意识到有时候,你在浏览器中得到的HTML页面可能与你用Scrapy请求得到的页面不同!根据我的经验,有些网站会用不同的HTML来响应,而不是你在浏览器中看到的HTML!这就是为什么有时如果您使用从浏览器中获取的“正确”xpath/css查询,如果在您的垃圾代码中使用它,它可能不会返回任何内容。 总是检查你的回应是否是你所期待的!在

已解决: 路径正确。我写错了起始网址!在


Tags: 代码httpsselfurl网站response选择器extract
2条回答

除了Desperado的答案,您还可以使用css选择器,这些选择器简单得多,但对于您的用例来说已经足够了:

$ scrapy shell "https://shop.app4health.it/"
In [1]: response.css('.level0 .level-top::attr(href)').extract()
Out[1]: 
['https://shop.app4health.it/sonno',
 'https://shop.app4health.it/monitoraggio-e-diagnostica',
 'https://shop.app4health.it/terapia',
 'https://shop.app4health.it/integratori-alimentari',
 'https://shop.app4health.it/fitness',
 'https://shop.app4health.it/benessere',
 'https://shop.app4health.it/ausili',
 'https://shop.app4health.it/prodotti-in-offerta',
 'https://shop.app4health.it/kit-regalo']

scrapy shell命令非常适合调试这样的问题。在

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

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

相关问题 更多 >