看起来很适合新手开发者!我只改变了你parse函数中的选择器:
for quote in response.css('div.block-list div.item'):
yield {
'text': quote.css('h3.headline::text').get(),
}
UPD:嗯,您的网站似乎提出了额外的数据请求。
打开开发者工具并检查对https://www.mckinsey.com/services/ContentAPI/SearchAPI.svc/search 的请求,参数为{"q":"Agile","page":1,"app":"","sort":"default","ignoreSpellSuggestion":false}。
您可以使用这些参数和适当的标头制作scrapy.Request,并获取带有数据的json。使用json lib 可以轻松解析。
UPD2:从这个 curl curl 'https://www.mckinsey.com/services/ContentAPI/SearchAPI.svc/search' -H 'content-type: application/json' --data-binary '{"q":"Agile","page”:1,”app":"","sort":"default","ignoreSpellSuggestion":false}' --compressed 可以看出,我们需要以这种方式发出请求:
from scrapy import Request
import json
data = {"q": "Agile", "page": 1, "app": "", "sort": "default", "ignoreSpellSuggestion": False}
headers = {"content-type": "application/json"}
url = "https://www.mckinsey.com/services/ContentAPI/SearchAPI.svc/search"
yield Request(url, headers=headers, body=json.dumps(data), callback=self.parse_api)
然后在parse_api 函数中只解析响应:
def parse_api(self, response):
data = json.loads(response.body)
# and then extract what you need
所以你可以在请求中迭代参数page并获取所有页面。
UPD3:工作解决方案:
from scrapy import Spider, Request
import json
class BrickSetSpider(Spider):
name = "brickset_spider"
data = {"q": "Agile", "page": 1, "app": "", "sort": "default", "ignoreSpellSuggestion": False}
headers = {"content-type": "application/json"}
url = "https://www.mckinsey.com/services/ContentAPI/SearchAPI.svc/search"
def start_requests(self):
yield Request(self.url, headers=self.headers, method='POST',
body=json.dumps(self.data), meta={'page': 1})
def parse(self, response):
data = json.loads(response.body)
results = data.get('data', {}).get('results')
if not results:
return
for row in results:
yield {'title': row.get('title')}
page = response.meta['page'] + 1
self.data['page'] = page
yield Request(self.url, headers=self.headers, method='POST', body=json.dumps(self.data), meta={'page': page})