1

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 シェルの実行からの元の応答と同じ形式ではありません。JSONとしてロードされていないようです。スクレイピーにはこれ専用の何かがあると思いますが、ドキュメントで見つけることができません。

編集 して、次のようにしてhtmlコンテンツを取得できます。

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

しかし、このユニコードから必要なデータを引き出すには、はるかに便利な組み込みの xpath セレクターではなく、正規表現を使用する必要があります。

このソリューションのように、Selenium または別のアドオンを使用しないことをお勧めします。スピードとシンプルさが最優先事項です。

4

2 に答える 2

2

Scrapy Selector のドキュメントは次のとおりです: http://doc.scrapy.org/en/1.1/topics/selectors.html

私は同じ質問に会いました。そしてSelectorで対処します。応答または文字列によってセレクターを作成できます。その後、「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.')
于 2016-08-09T09:11:46.100 に答える
0

HTML コンテンツを取得したら、xpath セレクターを使用するために Selector オブジェクトを初期化できます。

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)
于 2015-10-25T19:30:36.810 に答える