pyspider 使用PhantomJS渲染

2023-02-16 18:09 更新

有時網(wǎng)頁太復雜,無法找到API請求。現(xiàn)在是時候滿足PhantomJS的力量了。

要使用PhantomJS,你應該有PhantomJS 安裝。如果你正在使用all模式運行pyspider,那么如果可以在中刪除,則啟用PhantomJS PATH。

確保phantomjs正在運行

$ pyspider phantomjs

如果輸出是,繼續(xù)本教程的其余部分

Web server running on port 25555

使用PhantomJS

當連接PhantomJS的pyspider時,您可以通過添加參數(shù)fetch_type='js'來啟用此功能self.crawl。我們使用PhantomJS來抓取http://www.twitch.tv/directory/game/Dota 2的頻道列表,該列表 加載了我們在第2級中討論過的AJAX :

```
class Handler(BaseHandler):
    def on_start(self):
        self.crawl('http://www.twitch.tv/directory/game/Dota 2',
                   fetch_type='js', callback=self.index_page)

    def index_page(self, response):
        return {
            "url": response.url,
            "channels": [{
                "title": x('.title').text(),
                "viewers": x('.info').contents()[2],
                "name": x('.info a').text(),
            } for x in response.doc('.stream.item').items()]
        }
```

我使用了一些API來處理流列表。您可以從PyQuery完整API中找到完整的API參考

在頁面上運行JavaScript

我們將嘗試從本節(jié)中的http://www.pinterest.com/categories/popular/中刪除圖像。開頭只顯示25張圖像,滾動到頁面底部時會加載更多圖像。

要抓取盡可能多的圖像,我們可以使用js_script參數(shù)來設置一些函數(shù)包裝的JavaScript代碼來模擬滾動操作:

```
class Handler(BaseHandler):
    def on_start(self):
        self.crawl('http://www.pinterest.com/categories/popular/',
                   fetch_type='js', js_script="""
                   function() {
                       window.scrollTo(0,document.body.scrollHeight);
                   }
                   """, callback=self.index_page)

    def index_page(self, response):
        return {
            "url": response.url,
            "images": [{
                "title": x('.richPinGridTitle').text(),
                "img": x('.pinImg').attr('src'),
                "author": x('.creditName').text(),
            } for x in response.doc('.item').items() if x('.pinImg')]
        }
```

頁面加載后可以執(zhí)行腳本(可以通過js_run_at參數(shù)更改) 我們在頁面加載后滾動一次,您可以使用滾動多次setTimeout。在超時到達之前,PhantomJS將獲取盡可能多的項目。

在線演示:http://demo.pyspider.org/debug/tutorial_pinterest


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號