pyspider 使用PhantomJS渲染

2023-02-16 18:09 更新

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

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

確保phantomjs正在運(yùn)行

$ pyspider phantomjs

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

Web server running on port 25555

使用PhantomJS

當(dāng)連接PhantomJS的pyspider時(shí),您可以通過添加參數(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參考

在頁面上運(yùn)行JavaScript

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

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

```
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ù)更改) 我們在頁面加載后滾動(dòng)一次,您可以使用滾動(dòng)多次setTimeout。在超時(shí)到達(dá)之前,PhantomJS將獲取盡可能多的項(xiàng)目。

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


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號