我正在尝试抓取 ajax 请求后加载的数据。
例如,该 YouTube 页面的前 30 个视频以 html 形式显示,然后用户必须单击“加载更多”按钮,该按钮会触发 ajax 并获取更多结果。 https://www.youtube.com/user/testedcom/videos
我可以获得 ajax 链接,但是使用 Scrapy 功能提取剩余数据/“分页”的最佳方式是什么?
启动外壳:
scrapy shell https://www.youtube.com/user/testedcom/videos
获取ajax延续的url:
continuation_url = response.xpath('//*[@class="yt-uix-button yt-uix-button-size-default yt-uix-button-default load-more-button yt-uix-load-more browse-items-load-more-button"]/@data-uix-load-more-href').extract()[0]
url = "https://www.youtube.com/user/testedcom/videos" + continuation_url
从ajax调用获取新数据:
fetch(url)
...但是从这里我不知道如何处理这些数据。它与运行 scrapy shell 的原始响应的格式不同。它似乎不太作为 JSON 加载。我认为 scrapy 有专门用于此目的的东西,但在文档中找不到它。
编辑 我可以通过以下方式获取 html 内容:
import json
response_json = json.loads(response.body_as_unicode())
html = response_json['content_html']
但是我必须使用正则表达式从这个 unicode 中提取所需的数据,而不是使用更方便的内置 xpath 选择器。
最佳答案
这里是Scrapy Selector的文档:http://doc.scrapy.org/en/1.1/topics/selectors.html
我也遇到了同样的问题。我通过选择器来处理它。您可以通过响应或字符串构造一个选择器,然后可以使用'xpath'。
此外,您还可以使用try... except...
来识别响应的类型(html或json)
def parse(self, response):
try:
jsonresponse = json.loads(response.body_as_unicode())
html = jsonresponse['content_html'].strip()
sel = Selector(text=html)
except:
sel = Selector(response=response)
entries = sel.xpath(
'//li[contains(@class,"feed-item-container")]')
for entry in entries:
try:
title = entry.xpath('.//h3/a/text()').extract()[0]
item = YoutubeItem()
item['title'] = title
yield item
except Exception as err:
continue
try:
jsonresponse = json.loads(response.body_as_unicode())
sel = Selector(text=jsonresponse['load_more_widget_html'])
except:
sel = Selector(response=response)
try:
url = "https://www.youtube.com" + \
sel.xpath(
'//button[contains(@class,"load-more-button")]/@data-uix-load-more-href').extract()[0]
req = scrapy.Request(url, callback=self.parse)
yield req
except:
self.log('Scawl completed.')
关于python - Scrapy - 在shell和spider中处理ajax连续响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324265/