在shell和spid中处理ajax连续响应数据

2024-05-23 21:10:25 发布

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

我试图获取ajax请求后加载的数据。在

例如,youtube页面的前30个视频是用html显示的,然后用户必须单击一个“loadmore”按钮来触发ajax并获得更多结果。 https://www.youtube.com/user/testedcom/videos

我可以得到ajax链接,但是用蹩脚的特性提取剩余数据/“分页”的最佳方法是什么?

启动外壳:

scrapy shell https://www.youtube.com/user/testedcom/videos

获取ajax继续的url:

^{pr2}$

从ajax调用获取新数据:

fetch(url)

…但从这里我不知道该如何处理这些数据。它的格式与运行scrapy shell的原始响应的格式不同。它似乎没有完全加载为JSON。我想斯帕蒂有专门针对这方面的东西,但在文档中找不到。在

编辑 我可以通过以下操作获取html内容:

import json
response_json = json.loads(response.body_as_unicode())
html = response_json['content_html']

但是,我必须使用正则表达式从unicode中提取所需的数据,而不是使用更方便的内置xpath选择器。在

Would prefer to not use Selenium or another add-on like in this solution. Speed and simplicity is a priority.


Tags: 数据httpscomjsonurlyoutuberesponsehtml
2条回答

获取html内容后,可以初始化选择器对象以使用xpath选择器:

from scrapy.selector import Selector
import json

response_json = json.loads(response.body_as_unicode())
html = response_json['content_html']
sel = Selector(text=html)
for url in sel.xpath('//@href').extract():
    yield Request(url, callback=self.somecallbackfunction)

下面是废选择器的文档: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.')

相关问题 更多 >