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()函数,发送请求. 但是在真正 ...
随机推荐
- vue日记之可展开的消息气泡
项目小需求之聊天气泡可展开内容 因为某些信息内容太长或者某种原因必须分行输出,这就导致了有时候一个气泡占据了一整个聊天区域 所以我打算实现一个在该气泡加载的时候判断其气泡长度,并在长度过长的情况下进行 ...
- 使用Magicodes.IE快速导出Excel
前言 总是有很多朋友咨询Magicodes.IE如何基于ASP.NET Core导出Excel,出于从框架的体验和易用性的角度,决定对Excel的导出进行独立封装,以便于大家更易于使用,开箱即用. 注 ...
- CentOS 8.0 安装docker 报错:Problem: package docker-ce-3:19.03.4-3.el7.x86_64 requires containerd.io >= 1
1.错误内容 package docker-ce-3:19.03.2-3.el7.x86_64 requires containerd.io >= 1.2.2-3, but none of th ...
- Vue3学习第一例:Vue3架构入门
入门 Vue3的教程很少,官方网站实例不好整,另外由于Python的Django也掌握了,学习这个有些让人眼乱.Vue项目创建后,在public目录下面自动生成了一个index.htm,里面有个div ...
- Apache httpd的web服务
Apache httpd的web服务 适用于Unix/Linux下的web服务器软件 Apache httpd(开源且免费),虚拟主机,支持HTTPS协议,支持用户认证,支持单个目录的访问控制,支持U ...
- RHCE_DAY04
sed流式编辑器 sed是一个非交互的文本编辑器,实现的功能跟vim相同,主要是对文件内容进行输出.删除.替换.复制.剪切.导入.导出等功能 命令格式1:前置命令 | sed [选项] '[指令]' ...
- Skywalking-06:OAL基础
OAL 基础知识 基本介绍 OAL(Observability Analysis Language) 是一门用来分析流式数据的语言. 因为 OAL 聚焦于度量 Service . Service In ...
- 1056 Mice and Rice (25分)队列
1.27刷题2 Mice and Rice is the name of a programming contest in which each programmer must write a pie ...
- MongoDB-01-基础
mongodb逻辑结构 Mongodb 逻辑结构 MySQL逻辑结构 库 (database) 库 集合(collection) 表 文档(document) 数据行 安装部署 1 系统准备 1 这里 ...
- ESP32-S2原生USB 烧录 TinyUF2 bootloader 加 CircuitPython
概述 ESP32-S2最令我心仪的改进是原生支持USB,即带有一个集成了收发器的全速 USB OTG 外设,符合 USB 1.1 规范,理论速度1.5m/s,利用得当将会是一个非常巨大的进步. 目前E ...