聚焦Python分布式爬虫必学框架 Scrapy 打造搜索引擎
作者:
江湖十年 | 来源:发表于
2018-07-07 14:03 被阅读35次
技术选型

image.png
网页分类

image.png
爬虫能做什么

image.png
正则表达式

image.png
深度优先 和 广度优先

image.png
网站 URL 的结构

image.png
- 实际上网站 URL 设计是分层的,整个网站的 URL 是一个树形结构
网站 URL 链接的结构图

image.png
- 实际中的 URL 链接是会循环指向的,这样就会有爬虫陷阱,有可能两个链接相互指向,爬虫一直重复的在爬这两个链接,跳不出去,不会爬取其他页面。所以设计爬虫要加入 URL 去重功能。
假设有一个树结构

image.png
对以上的树结构,深度优先 和 广度优先 遍历顺序如下

image.png
深度优先算法代码思路

image.png
- Scrapy 默认采用深度优先算法
- 递归算法比较危险,如果不停做递归或者递归深度太深,会出现栈溢出现象
广度优先算法代码思路

image.png
爬虫 URL 去重策略

image.png
- 直接将 URL 保存到数据库中只是一种方法,但不可取,每次都去数据库查询这个 URL 是否已经存在数据库中,效率太低
- 将 URL 保存到 Python 的 set 中,由于 Python 默认 Unicode 编码,占用空间大,浪费内存资源
- 用 MD5 哈希后大小会被压缩,通常是 128 bit(计算机中最小的单元 bit),再保存到 set 中,Scrapy 中用的类似这种方法
字符串编码

image.png

image.png
- 实际上,现实编程场景中,我们编写代码的时候代码在内存中是 unicode 编码格式,因为这样内存处理起来简单,在保存到文件和传输过程中是 utf-8 编码格式,优点是自动伸缩字节长度,占用资源少

image.png
- python 中 encode() 方法试用于将 unicode 编码字符串转换成其他编码,decode() 方法是将其他编码格式转换成 unicode 字符串(python3 默认 unicode 编码)

image.png
本文标题:聚焦Python分布式爬虫必学框架 Scrapy 打造搜索引擎
本文链接:https://www.haomeiwen.com/subject/mpkehftx.html
网友评论