如果你想要 li's 中的 hrefs 和 evt-click 类,你可以使用以下 xpath:
xpath('//li[@class="evt-click"]/@href'))
在您自己的示例中,您需要:
xpath("./@href")
这两个都不起作用的原因是因为您提供的链接中的 html 中不存在您要查找的内容,有 11 个 li class="evt-click" 并且没有一个包含 a 标签内的 js 的任何 href 栏:
您可以使用scrapy-splash 让页面完全呈现以获取动态生成的数据,您需要按照链接说明进行安装:
添加到setting.py:
DOWNLOADER_MIDDLEWARES = {
'scrapyjs.SplashMiddleware': 725,
}
启动一个 docker 实例:
docker run -p 8050:8050 scrapinghub/splash:
那么这样就可以得到你想要的数据了:
import scrapy
class MySpider(scrapy.Spider):
name = "deez"
start_urls = ["http://www.deezer.com/profile/154723101"]
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url, self.parse, meta={
'splash': {
'endpoint': 'render.html',
'args': {'wait': 1}
}
})
def parse(self, response):
print(response.xpath("//li[@class='evt-click']").extract())
输出:
$ scrapy crawl deez
.............................
2016-03-20 23:01:12 [scrapy] DEBUG: Crawled (200) <POST http://127.0.0.1:8050/render.html> (referer: None)
[u'/profile/154723101/loved', u'/profile/154723101/playlists', u'/profile/154723101/albums', u'/profile/154723101/artists', u'/profile/154723101/radios', u'/profile/154723101/following', u'/profile/154723101/followers']
selenium 也是另一种选择。