爬虫

爬虫框架 scrapy

1、创建新项目

scrapy startproject tutorial

2、创建爬虫文件

# 创建普通模版
scrapy genspider 爬虫名字 爬取的域名(不用协议头)
# 创建 crawl spider 模版
scrapy genspider -t crawl 爬虫名字 爬取的域名(不用协议头)

3、启动爬虫

scrapy crawl 爬虫名字

项目文件结构

项目名字
	项目名字
		spiders文件夹(存储的是爬虫文件)
			init
			自定义的爬虫文件		核心功能文件
		init
		items		定义数据结构的地方		爬取的数据包含那些
		middleware		中间件		代理
		settings		配置文件		robots协议		ua定义等

response的属性和方法

response.text	获取的是响应的字符串
response.body	获取的是二进制数据
response.xpath	可以直接是xpath方法来解析response中的内容
response.extract()	提取seletor对象的data属性值
response.extract_first()	提取seletor列表的第一个数据

setting

# 需要使用管道,需要打开该设置
ITEM_PIPELINES = {
	# 管道可以有多个,并有有优先级,值从1-1000,值越小越高
	'项目名.pipelines.管道名': 300
}

下载图片

import urllib.request
class DownLoadPipeline:
    def process_item(self, item, spider):
        url = item.get('url')
        filename='http://'+ item.get('name')+'.jpg'
        urllib.request.urlretrieve(url = url, filename = filename)
        return item

部署

scrapy部署服务器有一套完整的开源项目:scrapy+scrapyd(服务端)+scrapy-client(客户端)+scrapydweb 1、scrapyd(服务端)

# 官方文档
https://scrapyd.readthedocs.io
# 安装
pipenv install scrapyd
# 启动
scrapyd
# 浏览器访问
http://127.0.0.1:6800

2、scrapy-client scrapy-client它允许我们将本地的scrapy项目打包发送到scrapyd 这个服务端(前提是服务器scrapyd正常运行)

# 官方文档
https://pypi.org/project/scrapyd-client/
# 安装
pipenv install scrapyd-client

3、scrapydweb(可选)

ScrapydWeb:用于Scrapyd集群管理的Web应用程序,支持Scrapy日志分析和可视化。

#官方文档
https://github.com/my8100/scrapydweb/blob/master/README_CN.md
# 安装
pipenv install scrapydweb
# 运行命令
scrapydweb

运行命令scrapydweb,首次启动将会在当前目录下生成配置文件“scrapydweb_settings_v*.py”

1、更改配置文件 编辑配置文件,将ENABLE_LOGPARSER更改为False

2、添加访问权限

SCRAPYD_SERVERS = [
    '127.0.0.1:6800',
    # 'username:password@localhost:6801#group',
    ('username', 'password', 'localhost', '6801', 'group'),
]

3、添加http认证

ENABLE_AUTH = True
USERNAME = 'username'
PASSWORD = 'password'

如果启动失败(一般是使用了高版本的python)

# 400 错误
APScheduler==3.9.1
# 500 错误
SQLAlchemy>=1.2.15,<1.4.0