首页 » PHP教程 » php怎么挪用plantomjs技巧_爬取动态js html数据方法二 运用phantomjs

php怎么挪用plantomjs技巧_爬取动态js html数据方法二 运用phantomjs

duote123 2024-11-06 0

扫一扫用手机浏览

文章目录 [+]

本系列文章紧张记录和讲解pyspider的示例代码,希望能抛砖引玉。
pyspider示例代码官方网站是http://demo.pyspider.org/。
上面的示例代码太多,无从下手。
因此本人找出一下比较经典的示例进行大略讲解,希望对新手有一些帮助。

示例解释:

php怎么挪用plantomjs技巧_爬取动态js html数据方法二 运用phantomjs

如果页面中部分数据或笔墨由js天生,pyspider不能直接提取页面的数据。
pyspider获取页面的代码,但是个中的js代码phantomjs,办理js代码实行问题。

php怎么挪用plantomjs技巧_爬取动态js html数据方法二 运用phantomjs
(图片来自网络侵删)

利用方法:

方法一:在self.crawl函数中添加fetch_type="js"调用phantomjs实行js代码。

方法二:为函数添加参数@config(fetch_type="js")。

示例代码:

1、www.sciencedirect.com网站示例

#!/usr/bin/env python

# -- encoding: utf-8 --

# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:

# Created on 2014-10-31 13:05:52

import re

from libs.base_handler import

class Handler(BaseHandler):

'''

this is a sample handler

'''

crawl_config = {

"headers": {

"User-Agent": "BaiDu_Spider",

},

"timeout":300,

"connect_timeout":100

}

def on_start(self):

self.crawl('http://www.sciencedirect.com/science/article/pii/S1568494612005741',timeout=300,connect_timeout=100,

callback=self.detail_page)

self.crawl('http://www.sciencedirect.com/science/article/pii/S0167739X12000581',timeout=300,connect_timeout=100,

age=0, callback=self.detail_page)

self.crawl('http://www.sciencedirect.com/science/journal/09659978',timeout=300,connect_timeout=100,

age=0, callback=self.index_page)

@config(fetch_type="js")

def index_page(self, response):

for each in response.doc('a').items():

url=each.attr.href

#print(url)

if url!=None:

if re.match('http://www.sciencedirect.com/science/article/pii/\w+$', url):

self.crawl(url, callback=self.detail_page,timeout=300,connect_timeout=100)

@config(fetch_type="js")

def detail_page(self, response):

self.index_page(response)

self.crawl(response.doc('#relArtList > li > .cLink').attr.href, callback=self.index_page,timeout=300,connect_timeout=100)

return {

"url": response.url,

"title": response.doc('.svTitle').text(),

"authors": [x.text() for x in response.doc('.authorName').items()],

"abstract": response.doc('.svAbstract > p').text(),

"keywords": [x.text() for x in response.doc('.keyword span').items()],

}

针对pyspider中看不到内容,再写爬虫脚本的时候,直接用phantomjs的方法

标签:

相关文章

SEO标签规范在网站优化中的应用与方法

搜索引擎优化(SEO)已经成为网站建设和运营的重要环节。SEO标签作为搜索引擎优化的重要手段,对于提高网站在搜索引擎中的排名具有重...

PHP教程 2025-04-07 阅读0 评论0

SEO标题优化方法,关键词布局的艺术

在互联网时代,搜索引擎优化(SEO)已成为企业提升网站排名、吸引潜在客户的重要手段。而SEO标题优化作为SEO策略的核心,对于提升...

PHP教程 2025-04-07 阅读0 评论0