scrapy shell xpath从itunes.apple.com

2024-03-28 20:49:28 发布

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

scrapy shell 'https://itunes.apple.com/us/album/no-tears-left-to-cry/1374085537?i=1374087460&v0=WWW-NAUS-ITSTOP100-SONGS&l=en&ign-mpt=uo%3D4'

我想从这里得到专辑“没有眼泪可以哭-单身”

Itunes chart _ music preview page "no tears left to cry - Single / Ariana Grande"

相册名称的xpath如下: //*[@id="ember653"]/section[1]/div/div[2]/div[1]/div[2]/header/h1

我试着

response.xpath('//*[@id="ember653"]/section[1]/div/div[2]/div[1]/div[2]/header/h1')

但结果是[]

我怎样才能从这个网站上得到唱片信息?你知道吗


Tags: tonohttpsdividsectionshellh1
2条回答

你最好不要使用JS渲染,它非常慢,很重,而且很麻烦。 花5分钟在Chrome的“网络”选项卡上查找数据源。它通常内置在页面源中,或者通过XHR请求传递。你知道吗

在这种情况下,您需要的所有数据都可以在页面本身上找到,但是您应该检查其源代码,而不是呈现的版本。在chrome中使用ctrl+u,然后ctrl+f找到所有需要的部件。你知道吗

import json

track_data = response.xpath('//script[@name="schema:music-album"]/text()').extract_first()
track_json = json.loads(track_data)
track_title = track_json['name']
yield {'title': track_title}

在这种情况下,它的工作速度是splash的5-7倍

这是因为scrapy不等待javascript加载,您需要使用scrapy-splashhere is my answer how you need to setup您的scrapy项目与scrapy-splash

如果我使用scrapy-splash,我会得到结果

2018-06-30 20:50:21 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://itunes.apple.com/us/album/no-tears-left-to-cry/1374085537?i=1374087460&v0=WWW-NAUS-ITSTOP100-SONGS&l=en&ign-mpt=uo%3D4%27 via http://localhost:8050/render.html> (referer: None)
2018-06-30 20:50:21 [scrapy.core.scraper] DEBUG: Scraped from <200 https://itunes.apple.com/us/album/no-tears-left-to-cry/1374085537?i=1374087460&v0=WWW-NAUS-ITSTOP100-SONGS&l=en&ign-mpt=uo%3D4%27>
{'title': 'no tears left to cry - Single'}

这是我的简单蜘蛛

import scrapy
from scrapy_splash import SplashRequest


class TestSpider(scrapy.Spider):
    name = "test"

    start_urls = ['https://itunes.apple.com/us/album/no-tears-left-to-cry/1374085537?i=1374087460&v0=WWW-NAUS-ITSTOP100-SONGS&l=en&ign-mpt=uo%3D4%27']

    def start_requests(self):
        for url in self.start_urls:
            yield SplashRequest(url=url,
                                callback=self.parse,
                                endpoint='render.html',
                                )

    def parse(self, response):
        yield {'title': response.xpath('//*[@id="ember653"]/section[1]/div/div[2]/div[1]/div[2]/header/h1//text()').extract_first()}

你也可以用scrapy shell来做这件事

scrapy shell 'http://localhost:8050/render.html?url=https://itunes.apple.com/us/album/no-tears-left-to-cry/1374085537?i=1374087460&v0=WWW-NAUS-ITSTOP100-SONGS&l=en&ign-mpt=uo%3D4'

In [2]: response.xpath('//*[@id="ember653"]/section[1]/div/div[2]/div[1]/div[2]/header/h1//text()').extract_first()
Out[2]: 'no tears left to cry - Single'

相关问题 更多 >