Python学习----pyspider(linux)(一)

官方文档:http://docs.pyspider.org/en/latest/

Anaconda使用请参考:https://blog.csdn.net/weixin_40132006/article/details/108629324

PhantomJS请参考:https://blog.csdn.net/weixin_40132006/article/details/108646199

Python学习----pyspider(linux)(二):https://blog.csdn.net/weixin_40132006/article/details/108683722

软件安装

pyspider安装

pip install pyspider

安装经历(Anaconda下)

在python3.8版本下

pip install pyspider

//出现错误
(base) bobo@bobo-PC:~$ pyspider
Traceback (most recent call last):
  File "/home/bobo/anaconda3/bin/pyspider", line 5, in <module>
    from pyspider.run import main
  File "/home/bobo/anaconda3/lib/python3.8/site-packages/pyspider/run.py", line 231
    async=True, get_object=False, no_input=False):
    ^
SyntaxError: invalid syntax
//因为python3.7以后async已经变成了关键字。因此出现这个错误。
修改方式是手动替换一下

下面位置的async改为mark_async
/usr/local/lib/python3.7/site-packages/pyspider/run.py 的231行、245行(两个)、365行
/usr/local/lib/python3.7/site-packages/pyspider/webui/app.py 的95行
/usr/local/lib/python3.7/site-packages/pyspider/fetcher/tornado_fetcher.py 的81行、89行(两个)、95行、117行
//太麻烦没有改

在python3.6版本下,一路坎坷

//注意更新pip
pip install --upgrade pip

//安装
pip install

//报错
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory

//解决方法
conda install pycurl

//报错
- Deprecated option 'domaincontroller': use 'http_authenticator.domain_controller' instead.

//解决方法
找打webdav.py,位置在  python3.6/site-packages/pyspider/webui
把 'domaincontroller': NeedAuthController(app),

修改为:

'http_authenticator':{
'HTTPAuthenticator':NeedAuthController(app),
},

//报错
ImportError: cannot import name 'DispatcherMiddleware'

//解决方法
conda install werkzeug

//报错
ImportError: cannot import name 'DispatcherMiddleware'

//解决方法
conda uninstall werkzeug
conda install werkzeug==0.16.0

//成功
(env_pyspider) bobo@bobo-PC:~$ pyspider all
[W 200917 12:27:58 run:413] phantomjs not found, continue running without it.
[I 200917 12:28:00 result_worker:49] result_worker starting...
[I 200917 12:28:00 processor:211] processor starting...
[I 200917 12:28:00 tornado_fetcher:638] fetcher starting...
[I 200917 12:28:00 scheduler:647] scheduler starting...
[I 200917 12:28:00 scheduler:782] scheduler.xmlrpc listening on 127.0.0.1:23333
[I 200917 12:28:00 scheduler:586] in 5m: new:0,success:0,retry:0,failed:0
[I 200917 12:28:01 app:76] webui running on 0.0.0.0:5000

如果出现pyspider的Web预览窗口太小,只需用以下所有代码更换python3.6/site-packages/pyspider/webui/static目录下debug.min.css文件所有代码

body{margin:0;padding:0;height:100%;overflow:hidden}.warning{color:#f0ad4e}.error{color:#d9534f}#control{z-index:9999;min-width:760px;width:100%;height:35px;position:fixed;left:0;right:0;background-color:#eee;box-shadow:0 1px 2px #999}#control div{line-height:35px;margin-left:10px;margin-right:10px}#control .webdav-btn{position:relative;float:right;padding:1px 7px 0;line-height:21px;border-radius:5px;border:1px solid #428bca;background:#fff;color:#428bca;cursor:pointer;margin:6px 0 0 10px}#control .webdav-btn:hover{background:#6aa3d5;color:#fff}#control .webdav-btn.active{background:#428bca;color:#fff}#editarea{width:100%;position:fixed;top:37px}#editarea,.debug-panel{left:0;right:0;bottom:0}.debug-panel{position:absolute;top:0}.resize{background-color:#555;cursor:ew-resize}.resize:hover+.debug-panel{border-left:1px dashed #555!important}.overlay{position:absolute;top:0;bottom:0;left:0;right:0;z-index:9999;background:rgba(0,0,0,.4)}.focus .CodeMirror-activeline-background{background:#e8f2ff!important}.CodeMirror-activeline-background{background:transparent!important}#task-panel{height:100%;overflow-x:auto}#run-task-btn{z-index:99;position:absolute;top:0;right:0;background:#5cb85c;border-radius:0 0 0 5px;color:#fff;margin:0;padding:3px 7px 5px 10px;cursor:pointer;font-weight:700;line-height:15px}#run-task-btn:hover{background:#449d44}#undo-redo-btn-group{z-index:99;position:absolute;top:0;right:0;background:#91cf91;border-radius:0 0 0 5px;color:#fff;margin:0;padding:3px 7px 5px 10px;cursor:pointer;font-weight:700;line-height:15px;top:auto;bottom:0;border-radius:5px 0 0 0;padding:5px 0 3px;overflow:hidden}#undo-redo-btn-group:hover{background:#6ec06e;background:#91cf91}#undo-redo-btn-group a{color:#fff;text-decoration:none;padding:5px 7px 3px 10px}#undo-redo-btn-group a:hover{background:#6ec06e}#save-task-btn{z-index:99;position:absolute;top:0;right:0;background:#428bca;border-radius:0 0 0 5px;color:#fff;margin:0;padding:3px 7px 5px 10px;cursor:pointer;font-weight:700;line-height:15px}#save-task-btn:hover{background:#3071a9}#task-editor{position:relative}#task-editor .CodeMirror{height:auto;padding-bottom:3px;background:#c7e6c7}#task-editor .CodeMirror-scroll{overflow-x:auto;overflow-y:hidden}#task-editor.focus .CodeMirror-activeline-background{background:#eaf6ea!important}#tab-control{list-style-type:none;position:absolute;bottom:0;right:0;margin:8px 20px;padding:0}#tab-control li{position:relative;float:right;padding:1px 7px 0;line-height:21px;margin-left:10px;border-radius:5px;border:1px solid #428bca;background:#fff;color:#428bca;cursor:pointer}#tab-control li:hover{background:#6aa3d5;color:#fff}#tab-control li.active{background:#428bca;color:#fff}#tab-control li span{position:absolute;top:-5px;right:-10px;background:#d9534f;color:#fff;font-size:80%;font-weight:700;padding:2px 5px 0;border-radius:10px}#debug-tabs{margin-bottom:45px}#tab-web.fixed{padding-top:24px}#tab-web iframe{border-width:0;width:100%;height:900px !important}#tab-html{margin:0;padding:7px 5px}#tab-html pre{margin:0;padding:0}#tab-follows .newtask{position:relative;height:30px;line-height:30px;background:#fceedb;border-bottom:1px solid #f0ad4e;border-top:1px solid #f0ad4e;margin-top:-1px;padding-left:5px;padding-right:70px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;cursor:pointer}#tab-follows .newtask:hover,#tab-follows .newtask:hover .task-more{background:#f8d9ac}#tab-follows .newtask .task-callback{color:#ec971f}#tab-follows .newtask .task-url{font-size:95%;text-decoration:underline;font-weight:lighter;color:#428bca}#tab-follows .newtask .task-more{position:absolute;right:33px;top:0;float:right;color:#f0ad4e;padding:0 10px;background:#fceedb;border-radius:10px}#tab-follows .newtask .task-run{position:absolute;right:0;top:0;font-size:80%;padding:0 10px 0 30px;float:right;border-bottom:1px solid #a3d7a3;border-top:1px solid #a3d7a3;background:#80c780;color:#fff;text-shadow:0 0 10px #fff;font-weight:700}#tab-follows .newtask .task-run:hover{background:#5cb85c}#tab-follows .task-show pre{margin:5px 5px 10px}#python-editor{position:absolute;top:0;width:100%;bottom:0}#python-editor .CodeMirror{height:100%;padding-bottom:20px}#python-log{width:100%;min-height:10px;max-height:40%;background:rgba(0,0,0,.6);overflow:auto}#python-log #python-log-show{z-index:89;width:auto;padding-top:5px;background:#d9534f;box-shadow:0 2px 20px #d9534f;cursor:pointer}#python-log pre{margin:0;padding:10px;color:#fff}#css-selector-helper{background-color:#eee;padding:0;width:100%;height:24px;text-align:right;white-space:nowrap}#css-selector-helper.fixed{position:absolute;top:0}#css-selector-helper button{line-height:16px;vertical-align:2px}span.element{position:relative;height:24px;display:inline-block;padding:0 .2em;cursor:pointer;color:#afafaf;z-index:99999}span.element.invalid{display:none}span.element.selected{color:#000}span.element:hover{background-color:#c8c8c8}span.element:hover>ul{display:block}span.element>ul{display:none;margin:0;padding:0;position:absolute;top:24px;left:0;background-color:#eee;border:1px solid #000;border-top-width:0;color:#afafaf}span.element>ul>li{display:block;text-align:left;white-space:nowrap;padding:0 4px}span.element>ul>li.selected{color:#000}span.element>ul>li:hover{background-color:#c8c8c8}.copy-selector-input{height:24px;padding:0;border:0;margin:0;padding-right:.2em;font-size:1em;text-align:right;width:100%;margin-left:-100px;background:#eee}
/*# sourceMappingURL=debug.min.css.map*/

框架介绍

该框架是由国人binux编写的强大的网络爬虫系统,其github地址为https://github.com/binux/pyspider ,带有WebUI、脚本编辑器、任务监控器、项目管理器以及结果处理器,支持多种数据库后端、多种消息队列、JavaScript渲染页面的爬取,使用起来方便。

Schedule发起任务调度,Fetcher负责抓取网页内容,Processer负责解析网页内容,然后将新生成的Request发给Schedule进行调度,将生成的提取结果输出保存。

功能简介

启动pyspider

pyspider all
phantomjs fetcher running on port 25555
[I 200918 09:46:19 result_worker:49] result_worker starting...
[I 200918 09:46:20 processor:211] processor starting...
[I 200918 09:46:20 tornado_fetcher:638] fetcher starting...
[I 200918 09:46:20 scheduler:647] scheduler starting...
[I 200918 09:46:20 scheduler:782] scheduler.xmlrpc listening on 127.0.0.1:23333
[I 200918 09:46:20 scheduler:126] project qunar updated, status:STOP, paused:False, 0 tasks
[I 200918 09:46:20 scheduler:126] project shares updated, status:TODO, paused:False, 0 tasks
[I 200918 09:46:20 scheduler:586] in 5m: new:0,success:0,retry:0,failed:0
[I 200918 09:46:20 app:76] webui running on 0.0.0.0:5000

打开网址:http://localhost:5000/

点击create按钮创建项目,输入项目Name和项目开始URL,创建项目。

创建项目之后会转到调试页面,左侧是调试区,右侧是代码区,刚开始有自动生成的初始代码

右侧代码区

from pyspider.libs.base_handler import *


class Handler(BaseHandler):
    crawl_config = {
    }

    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl('startURL', callback=self.index_page)

    @config(age=10 * 24 * 60 * 60)
    def index_page(self, response):
        for each in response.doc('a[href^="http"]').items():
            self.crawl(each.attr.href, callback=self.detail_page)

    @config(priority=2)
    def detail_page(self, response):
        return {
            "url": response.url,
            "title": response.doc('title').text(),
        }

Hander是pyspider爬虫的主类,定义爬取、解析、存储的逻辑。

crawl_config属性是定义本项目所有爬取配置,如定义Headers、设置代理等,配置之后全局生效。

on_start()是爬取入口,初始爬取请求会在这里产生。

调用crawl()方法可新建一个爬取请求,该方法第一个参数与是爬取URL地址,第二个参数是callback,指定这个页面爬取成功后用哪个方法进行解析。

index_page()方法接受response参数,也就是页面返回参数,我们直接调用doc()方法传入相应的CSS选择器。

detail_page()主要负责详情页的信息解析,解析之后将结果以字典的形式返回。

代码编写完成点击右上角save按钮保存后再执行。

左侧调试区

上侧代码

{
  "process": {
    "callback": "on_start"       //说明运行后执行的方法是执行了on_start()方法
  },
  "project": "qunar",
  "taskid": "data:,on_start",
  "url": "data:,on_start"
}

点击此代码右上角run按钮,运行执行on_start()方法。

下侧是调试结果显示界面,下方按钮

enable css selector helper-----------css选择器,浏览web视图,可以快速选择网页中的控件,可复制或者直接修改右侧代码。

web-------------------------------------------链接网页显示

html-------------------------------------------网页源码显示

follows---------------------------------------显示“callback”中方法执行后,方法中将要去爬取的所有网页链接,也就是crawl()方法中的URL,点击链接右侧的三角形开始按钮,开始执行爬取该链接

message-------------------------------------显示一些信息

{
  "fetch": {},
  "process": {
    "callback": "index_page"
  },
  "project": "qunar",
  "schedule": {
    "age": 864000
  },
  "taskid": "40ef55b952f0269ad202d55341efa50b",
  "url": "http://travel.qunar.com/travelbook/list.htm?order=hot_heat"
}

主页项目区

点击 Recent Active Tasks,即可查看最近所有请求的详细状况。

主页中可以查看已经创建的项目,一个表单:

group                                     项目分组,由于没有项目删除按钮,用户可将分组设置为delete,状态设置为stop,24小时自动删除。

project name                        项目名字

status                                     项目状态,点击有下拉框可更改,项目在RUNNING或者DEBUG可运行,TODO表示正在开发

rate/burst                               rate 代表 1 秒发出多少个请求,burst 相当于流量控制中的令牌桶算法的令牌数,rate 和 burst 设置的越大,爬取速率越快,当然速率需要考虑本机性能和爬取过快被封的问题。

avg time                                平均时间

progress                               process 中的 5m、1h、1d 指 的是最近 5 分、1 小时、1 天内的请求情况,all 代表所有的请求情况。请求由不同颜色表示、蓝色的代表等待被执行的请求,绿色的代表成功的请求,黄色的代表请求失败后等待重试的请求,红色的代表失败次数过多而被忽略的请求,这样可以直观知道爬取的进度和请求情况。

actions                                  点击 run 开始运行,点击 Active Tasks,即可查看最近项目请求的详细状况。点击 Result,即可查看所有的爬取结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值