python3 爬虫五大模块之五:信息采集器
Python的爬虫框架主要可以分为以下五个部分:
爬虫调度器:用于各个模块之间的通信,可以理解为爬虫的入口与核心(main函数),爬虫的执行策略在此模块进行定义;
URL管理器:负责URL的管理,包括带爬取和已爬取的URL、已经提供相应的接口函数(类似增删改查的函数)
网页下载器:负责通过URL将网页进行下载,主要是进行相应的伪装处理模拟浏览器访问、下载网页
网页解析器:负责网页信息的解析,这里是解析方式视具体需求来确定
信息采集器:负责将解析后的信息进行存储、显示等处理
代码示例是爬取CSDN博主下的所有文章为例,文章仅作为笔记使用,理论知识rarely
一、信息采集器简介
信息采集器的功能基本是将解析后的信息进行显示、存储到本地磁盘上。
信息采集器也许名字并不正确,自己突发奇想来的。我对解析器和采集器的区分不是很明确,在下面的示例中可能在采集器中依然进行了网页解析,主要原因在于对python的基本语法不熟,有些数据统一处理还不会,只能边解析边存储了。
二、信息采集器示例:(爬取CSDN博主下的所有文章)
# author : s260389826
# date : 2019/3/22
# position: chengdu
from fake_useragent import UserAgent
import urllib.request as request
from bs4 import BeautifulSoup
import urllib.parse
import os
import tomd
class HtmlOutputer(object):
# Replace deny char, used to name a directory.
def replace_deny_char(self, title):
deny_char = ['\\', '/', ':', '*', '?', '\"', '<', '>', '|', ':']
for char in deny_char:
title = title.replace(char, ' ')
print('Article\'title is: %s' % title)
return title
def img_download(self, img_url, directory, n):
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', str(UserAgent().random))]
urllib.request.install_opener(opener)
try:
img_name = '%s\%s.jpg' % (directory, n)
if os.path.exists(img_name) is True:
return
request.urlretrieve(img_url, img_name)
print('图片%d下载操作完成' % n)
except Exception as e:
print(e)
def collect(self, author, seq, html):
soup = BeautifulSoup(html,'html.parser', from_encoding='utf-8')
try:
# <h1 class="title-article">Windos下通过Wpcap抓包实现两个网卡桥接</h1>
article_title = soup.find('h1',attrs={'class': "title-article"}).text # 获取文章标题 print(soup.h1.text)
# <span class="time">2018年12月18日 16:43:02</span>
# article_time = soup.find('span',attrs={'class': "time"}).text # 获取文章时间
# assert isinstance(article_time, object)
# <span class="read-count">阅读数:104</span>
# article_readcnt= soup.find('span', attrs={'class': "read-count"}).text # 获取文章阅读量
# print(article_title, article_time, article_readcnt)
except AttributeError as e:
#print(e.reason)
return
article_title_convert = self.replace_deny_char(article_title)
directory = "F:\python\CSDN\\blog\%s\%d.%s" % (author, seq, article_title_convert)
if os.path.exists(directory) is False:
os.makedirs(directory)
# download blog'imgs:
# <div id="article_content">
imgs = soup.find('div', attrs={'id' : "article_content"}).findAll('img')
if len(imgs) > 0:
count = 0
for img in imgs:
count = count + 1
# print(img.attrs['src'])
self.img_download(img.attrs['src'], directory, count)
# down blog's ariticles: 如果要保存文件,需要将注释打开
'''
article = soup.find('div', attrs={'id' : "article_content"})
md = tomd.convert(article.prettify())
try:
with open('%s\%s.md' % (directory, article_title_convert), 'w', encoding='utf-8') as f:
f.write(md)
except FileNotFoundError as e:
print("No such file or directory: %s\%s" % (directory, article_title_convert))
'''
三、上述代码用到的知识点:
1. 对系统目录及文件的处理:
directory = "F:\python\CSDN\\blog\s2603898260"
if os.path.exists(directory) is False: # 如果该目录不存在
os.makedirs(directory) # 则进行创建目录 file_name = "F:\python\CSDN\\blog\s2603898260\log.txt"
if os.path.exists(file_name) is True: # 如果该文件存在
return # 不需要重新下载,直接返回
2. 特殊字符不能做文件名处理:
# Replace deny char, used to name a directory.
def replace_deny_char(self, title):
deny_char = ['\\', '/', ':', '*', '?', '\"', '<', '>', '|', ':']
for char in deny_char:
title = title.replace(char, ' ')
print('Article\'title is: %s' % title)
return title
3. 根据URL下载图片:
request.urlretrieve(img_url, img_name) # 根据img_url 下载图片到本地img_name(完整目录+图片名.格式)
def img_download(self, img_url, directory, n):
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', str(UserAgent().random))]
urllib.request.install_opener(opener)
try:
img_name = '%s\%s.jpg' % (directory, n)
if os.path.exists(img_name) is True:
return
request.urlretrieve(img_url, img_name)
print('图片%d下载操作完成' % n)
except Exception as e:
print(e)
4. tomd插件:
作用就是将html格式转换为td的格式。没理解错就是它:

不是很懂,我的下载转换效果也不是很好,
直接附链接:https://github.com/gaojiuli/tom
以及阅读td文件的链接:http://markdownpad.com/download.html
python3 爬虫五大模块之五:信息采集器的更多相关文章
- python3 爬虫五大模块之三:网页下载器
Python的爬虫框架主要可以分为以下五个部分: 爬虫调度器:用于各个模块之间的通信,可以理解为爬虫的入口与核心(main函数),爬虫的执行策略在此模块进行定义: URL管理器:负责URL的管理,包括 ...
- python3 爬虫五大模块之二:URL管理器
Python的爬虫框架主要可以分为以下五个部分: 爬虫调度器:用于各个模块之间的通信,可以理解为爬虫的入口与核心(main函数),爬虫的执行策略在此模块进行定义: URL管理器:负责URL的管理,包括 ...
- python3 爬虫五大模块之一:爬虫调度器
Python的爬虫框架主要可以分为以下五个部分: 爬虫调度器:用于各个模块之间的通信,可以理解为爬虫的入口与核心(main函数),爬虫的执行策略在此模块进行定义: URL管理器:负责URL的管理,包括 ...
- python3 爬虫五大模块之四:网页解析器
Python的爬虫框架主要可以分为以下五个部分: 爬虫调度器:用于各个模块之间的通信,可以理解为爬虫的入口与核心(main函数),爬虫的执行策略在此模块进行定义: URL管理器:负责URL的管理,包括 ...
- python3爬虫lxml模块的安装
1:在下载lxml之前,要先查看python的版本信息, 在CMD命令行输入python 再输入import pip; print(pip.pep425tags.get_supported()) -- ...
- [实战演练]python3使用requests模块爬取页面内容
本文摘要: 1.安装pip 2.安装requests模块 3.安装beautifulsoup4 4.requests模块浅析 + 发送请求 + 传递URL参数 + 响应内容 + 获取网页编码 + 获取 ...
- Python3爬虫系列:理论+实验+爬取妹子图实战
Github: https://github.com/wangy8961/python3-concurrency-pics-02 ,欢迎star 爬虫系列: (1) 理论 Python3爬虫系列01 ...
- python基础系列教程——Python3.x标准模块库目录
python基础系列教程——Python3.x标准模块库目录 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata ...
- Python3:Requests模块的异常值处理
Python3:Requests模块的异常值处理 用Python的requests模块进行爬虫时,一个简单高效的模块就是requests模块,利用get()或者post()函数,发送请求. 但是在真正 ...
随机推荐
- Linux--文件描述符、文件指针、索引节点
Linux -- 文件描述符 文件描述符 Fd 当进程打开文件或创建新文件时,内核会返回一个文件描述符(非负整数),用来指向被打开的文件,所有执行I/O操作的系统调用(read.write)都会通过文 ...
- P2470 压缩 TJ
前言 洛谷题解 题目传送门 正解:区间/线性 dp(本篇题解介绍线性做法) 人生第一道紫题! 也是今天考试看自闭了就没做的 T4,结果没想到是紫,虽然是一道水紫呢-- 考试的 T5 是跳房子,蓝题 q ...
- 7.算法竞赛中的常用JAVA API :String 、StringBuilder、StringBuffer常用方法和区别(转载)
7.算法竞赛中的常用JAVA API :String .StringBuilder.StringBuffer常用方法和区别 摘要 本文将介绍String.StringBuilder类的常用方法. 在j ...
- 实战爬取拷背漫画-Python
一.抓包获取链接 以爬取<前科者>为例 获取搜索链接 https://api.copymanga.com/api/v3/search/comic?limit=5&q=前科者 ...
- 在Ant脚本中使用时间戳
时间戳在项目自动构建中广泛使用,例如在jar文件的manifest文件中,以及最后zip包的文件名里等,时间戳对应的Ant命令是,这个标签既可以用在一个内部,也可以放在外部用作"全局&quo ...
- HandlerInterceptor与WebRequestInterceptor的异同
相同点 两个接口都可用于Contrller层请求拦截,接口中定义的方法作用也是一样的. //HandlerInterceptor boolean preHandle(HttpServletReques ...
- Redis-01-基础
基本概念 1 基本概念 redis是一个开源的.使用C语言编写的.支持网络交互的.可基于内存也可持久化的Key-Value数据库(非关系性数据库) redis运维的责任 1.保证服务不挂 2.备份数据 ...
- Windows常用命令汇总以及基础知识
命令部分: dir dir指定要列出的驱动器.目录和/或文件 ,/?显示所有命令 例:dir /b /s /o:n /a:a 表示显示当前路径下的所有文件的绝对路径,包含子文件夹的内容 /b表示去除摘 ...
- Java序列化bean保存到本地文件中
File file = new File("D:\\softTemp\\student.out"); ObjectOutputStream objectOutputStream = ...
- 如何在HTML中实现图片的滚动效果
<MARQUEE onmouseover=stop() onmouseout=start() scrollAmount=3 loop=infinite deplay="0"& ...